"""Context-selection latency: DeepCQ vs BM25 vs dense embedding retrieval.

Memory is sized like the paper's stock context (~44k tokens across sections).
Timing is per request, selection step only (no LLM call).

Two scenarios are measured for every method:
  * "changing": live state changes every turn (the realistic agent case).
      DeepCQ  - state re-set before each query, so its extraction cache is cold.
      BM25    - index rebuilt over all chunks before each query.
      Dense   - live-state chunks re-embedded each query; long-term chunks stay cached.
  * "static": memory unchanged between queries; every method reuses its cache/index.
Only the selection step is timed (no LLM call). Run: python context_selection_latency.py
Requires: deepcq rank_bm25 tiktoken sentence-transformers (CPU torch).
"""
import json
import platform
import random
import re
import statistics
import time

import numpy as np
import tiktoken
from deepcq import DeepCQ, MemorySchema
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer

random.seed(7)
enc = tiktoken.get_encoding("cl100k_base")

VOCAB = {
    "volume": "volume shares traded average daily turnover spike session block print liquidity float".split(),
    "news": "headline announcement press report analyst catalyst regulator export controls guidance chips".split(),
    "fundamentals": "revenue earnings eps margin cash flow ebitda capex balance sheet dividend quarter".split(),
    "insider": "insider ceo cfo officer form 4 purchase sale ownership director filing".split(),
    "filings": "10-k 10-q 8-k sec edgar proxy filing risk factors segment disclosure".split(),
    "indicators": "rsi macd moving average support resistance trend breakout momentum bollinger".split(),
    "thesis": "thesis conviction valuation scenario upside downside catalyst moat view position".split(),
}
FILLER = "the company reported that during period compared with prior levels while market participants noted".split()
# Target total ~44k tokens (paper: ~44,000-token stock context).
TARGET_TOKENS = {"volume": 4000, "news": 14000, "fundamentals": 5000, "insider": 3000,
                 "filings": 6000, "indicators": 4000, "thesis": 8000}


def section_text(name, n_tokens):
    words, out = VOCAB[name], []
    while len(enc.encode(" ".join(out))) < n_tokens:
        sent = [random.choice(words if random.random() < 0.35 else FILLER) for _ in range(18)]
        out.append(" ".join(sent).capitalize() + ".")
        if len(out) % 6 == 0:
            out.append("\n\n")
    return " ".join(out)


SECTIONS = {k: section_text(k, v) for k, v in TARGET_TOKENS.items()}
LIVE = [s for s in SECTIONS if s != "thesis"]
total_tokens = sum(len(enc.encode(t)) for t in SECTIONS.values())

QUERIES = [
    "what were Q4 earnings and eps?", "any news on export controls?", "show insider purchases by the ceo",
    "summarise the latest 10-q risk factors", "is rsi signalling a breakout?", "how did trading volume spike today?",
    "update my thesis on valuation", "compare margin and cash flow", "any analyst headlines this week?",
    "what does macd say about the trend?", "did any officer file a form 4?", "what is the dividend and capex plan?",
]
N = 400

# ---- DeepCQ -------------------------------------------------------------
cq = DeepCQ(schema=MemorySchema(sections=list(SECTIONS)))
cq.notes.append("thesis", f"[thesis]\n{SECTIONS['thesis']}")


def refresh_state():
    for s in LIVE:
        cq.state.set(s, f"[{s}]\n{SECTIONS[s]}")


def run_deepcq(q):
    return cq.query(q).sections_included


# ---- Chunks shared by BM25 / embeddings ----------------------------------
chunks = []
for name, text in SECTIONS.items():
    for para in [p.strip() for p in text.split("\n\n") if p.strip()]:
        chunks.append((name, para))
tok = lambda s: re.findall(r"[a-z0-9]+", s.lower())

bm25 = BM25Okapi([tok(c[1]) for c in chunks])


def run_bm25(q, k=8):
    scores = bm25.get_scores(tok(q))
    top = np.argpartition(scores, -k)[-k:]
    return sorted({chunks[i][0] for i in top})


model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", device="cpu")
t0 = time.perf_counter()
chunk_emb = model.encode([c[1] for c in chunks], normalize_embeddings=True, batch_size=64)
index_build_s = time.perf_counter() - t0


def run_embed(q, k=8):
    qv = model.encode([q], normalize_embeddings=True)[0]
    sims = chunk_emb @ qv
    top = np.argpartition(sims, -k)[-k:]
    return sorted({chunks[i][0] for i in top})


def bench(fn, before=None):
    for q in QUERIES[:4]:  # warm-up
        if before: before()
        fn(q)
    times = []
    for i in range(N):
        q = QUERIES[i % len(QUERIES)]
        if before: before()
        t = time.perf_counter()
        fn(q)
        times.append((time.perf_counter() - t) * 1000)
    times.sort()
    return {"p50_ms": round(statistics.median(times), 3),
            "p95_ms": round(times[int(0.95 * len(times)) - 1], 3),
            "mean_ms": round(statistics.fmean(times), 3)}


LIVE_CHUNKS = [i for i, c in enumerate(chunks) if c[0] != "thesis"]


def rebuild_bm25():
    global bm25
    bm25 = BM25Okapi([tok(c[1]) for c in chunks])


def reembed_live():
    chunk_emb[LIVE_CHUNKS] = model.encode([chunks[i][1] for i in LIVE_CHUNKS],
                                          normalize_embeddings=True, batch_size=64)


def timed(fn, before):
    # Time the refresh/re-index together with the query for the "changing" scenario.
    def step(q):
        before()
        return fn(q)
    return step


results = {
    "changing": {
        "deepcq": bench(run_deepcq, refresh_state),  # refresh not timed: writing state is the agent's cost, not selection
        "bm25": bench(timed(run_bm25, rebuild_bm25)),
    },
    "static": {
        "deepcq": bench(run_deepcq),
        "bm25": bench(run_bm25),
        "dense": bench(run_embed),
    },
}
N = 20  # re-embedding takes seconds per query
results["changing"]["dense"] = bench(timed(run_embed, reembed_live))
meta = {
    "memory_tokens": total_tokens, "sections": len(SECTIONS), "chunks": len(chunks), "runs_per_method": {"default": 400, "dense_changing": 20},
    "embedding_index_build_s": round(index_build_s, 2),
    "cpu": "AMD Ryzen 5 5600X (6C/12T)", "embedding_model": "all-MiniLM-L6-v2 (CPU)", "chunks_retrieved_k": 8, "python": platform.python_version(),
    "deepcq_version": __import__("importlib.metadata").metadata.version("deepcq"),
}
print(json.dumps({"meta": meta, "results": results}, indent=2))
