"""Exact vs semantic cache on a simulated query log.
Intents = headings from the FastAPI docs. Each query = intent phrased with a random template.
Zipf-distributed intent popularity. A semantic hit is 'wrong' if the matched cached query
has a different intent than the incoming query. Embeddings: bge-small-en-v1.5 (fastembed)."""
import re, glob, random, time, platform, sys
import numpy as np
from fastembed import TextEmbedding
import fastembed

random.seed(7); rng = np.random.default_rng(7)
heads = []
for f in sorted(glob.glob("experiments/corpus/*.md")):
    for line in open(f, encoding="utf-8"):
        m = re.match(r"^#{2,3} (.+?)(\s*\{.*\})?\s*$", line)
        if m:
            h = re.sub(r"[`*\[\]()]", "", m.group(1)).strip()
            if 2 <= len(h.split()) <= 8 and h.lower() not in [x.lower() for x in heads]:
                heads.append(h)
random.shuffle(heads)
heads = heads[:1500]
T = ["how do I {h} in FastAPI", "{h}", "FastAPI {h}", "what is the way to {h}", "explain {h}",
     "can you show me {h} please", "{h} example", "help with {h} in my FastAPI app", "docs on {h}"]
def phrase(h, t): return t.format(h=h if t != T[0] and t != T[3] else h.lower())
N = 20000
ranks = np.arange(1, len(heads) + 1)
p = 1 / ranks**1.0; p /= p.sum()
intent = rng.choice(len(heads), size=N, p=p)
tmpl = rng.integers(0, len(T), size=N)
queries = [phrase(heads[i], T[t]) for i, t in zip(intent, tmpl)]
# casual noise: random case / trailing space on 30% (what exact cache normalisation handles)
queries = [q.upper() if random.random() < .1 else q for q in queries]

model = TextEmbedding("BAAI/bge-small-en-v1.5")
uq = sorted(set(queries))
t0 = time.time(); E = np.array(list(model.embed([u.lower() for u in uq])), dtype=np.float32)
emb_s = time.time() - t0
E /= np.linalg.norm(E, axis=1, keepdims=True)
eidx = {u: i for i, u in enumerate(uq)}
V = np.stack([E[eidx[q]] for q in queries])

print(f"intents={len(heads)} queries={N} unique_strings={len(uq)} embed_ms_per_query={1000*emb_s/len(uq):.2f}")
print(f"python {platform.python_version()} numpy {np.__version__} fastembed {fastembed.__version__}")

def run(thr, norm_exact=True):
    """Exact cache first (normalised string), then semantic with threshold thr (None = exact only)."""
    seen = {}; mat = np.zeros((N, V.shape[1]), np.float32); owner = []; n = 0
    hit = wrong = exact_hit = 0
    for k, q in enumerate(queries):
        key = q.lower().strip()
        if key in seen:
            hit += 1; exact_hit += 1
            if seen[key] != intent[k]: wrong += 1
            continue
        if thr is not None and n:
            s = mat[:n] @ V[k]; j = int(s.argmax())
            if s[j] >= thr:
                hit += 1
                if owner[j] != intent[k]: wrong += 1
                continue
        seen[key] = intent[k]
        if thr is not None: mat[n] = V[k]; owner.append(intent[k]); n += 1
    return hit, exact_hit, wrong

print("\nthreshold | hit rate | of which exact | wrong hits (% of hits) | wrong (% of all queries)")
for thr in [None, 0.98, 0.95, 0.92, 0.90, 0.88, 0.85, 0.80, 0.75]:
    h, e, w = run(thr)
    print(f"{'exact only' if thr is None else thr:>10} | {100*h/N:5.1f}% | {100*e/N:5.1f}% | {w:4d} ({100*w/max(h,1):4.1f}%) | {100*w/N:4.2f}%")

# lookup cost of the semantic scan (brute force numpy) at cache size n
print("\ncache size | brute-force lookup ms (1 query, 384 dim)")
for n in [1000, 10000, 100000]:
    M = rng.standard_normal((n, 384)).astype(np.float32); q = M[0]
    t0 = time.perf_counter()
    for _ in range(50): int((M @ q).argmax())
    print(f"{n:>10} | {1000*(time.perf_counter()-t0)/50:.3f}")

# staleness: at query 10000, 5% of intents change their source doc. No invalidation vs TTL.
print("\nstaleness: 5% of intents updated at query 10000 (hot intents included)")
changed = set(rng.choice(len(heads), size=int(.05 * len(heads)), replace=False).tolist())
def stale(thr, ttl):
    seen = {}; mat = np.zeros((N, V.shape[1]), np.float32); owner = []; born = []; n = 0
    hits = st = 0; keys = []
    for k, q in enumerate(queries):
        key = q.lower().strip(); found = None
        if key in seen and (ttl is None or k - seen[key][1] <= ttl): found = seen[key]
        elif thr is not None and n:
            s = mat[:n] @ V[k]; j = int(s.argmax())
            if s[j] >= thr and (ttl is None or k - born[j] <= ttl): found = (owner[j], born[j])
        if found:
            hits += 1
            if k >= 10000 and found[1] < 10000 and intent[k] in changed: st += 1
        else:
            seen[key] = (intent[k], k)
            if thr is not None: mat[n] = V[k]; owner.append(intent[k]); born.append(k); n += 1
    return hits, st
print("policy | hit rate | stale answers served (count, % of queries after update)")
for name, thr, ttl in [("exact, no TTL", None, None), ("exact, TTL 2000 q", None, 2000), ("exact, TTL 500 q", None, 500),
                       ("semantic 0.92, no TTL", .92, None), ("semantic 0.92, TTL 2000 q", .92, 2000), ("semantic 0.92, TTL 500 q", .92, 500)]:
    h, s = stale(thr, ttl)
    print(f"{name:26} | {100*h/N:5.1f}% | {s:4d} ({100*s/10000:.2f}%)")
