"""Interview question: 'How do you choose top-k?' BM25 over heading-aware FastAPI doc chunks.
Queries: 2+ token headings (seed 0, 300 sampled) and 8-random-token queries from a chunk (200).
Reports recall@k and the mean context size (chars) that k chunks would add to the prompt."""
import glob, re, random, math, platform
from collections import Counter, defaultdict
TOKEN = re.compile(r"\w+")
tok = lambda t: TOKEN.findall(t.lower())
chunks, heads = [], []
for fn in sorted(glob.glob("experiments/corpus/*.md")):
    cur, title = [], ""
    for line in open(fn, encoding="utf-8").read().splitlines() + ["# END"]:
        if re.match(r"#{1,4} ", line):
            body = " ".join(cur).strip()
            if len(body) > 200: chunks.append(title + " " + body); heads.append(title)
            cur, title = [], line.lstrip("# ").strip()
        else: cur.append(line)
docs = [tok(c) for c in chunks]; N = len(docs); avg = sum(map(len, docs)) / N
post = defaultdict(list)
for i, d in enumerate(docs):
    for t, f in Counter(d).items(): post[t].append((i, f))
idf = {t: math.log(1 + (N - len(p) + .5) / (len(p) + .5)) for t, p in post.items()}
def top(q, k):
    s = defaultdict(float)
    for t in q:
        for i, f in post.get(t, []):
            s[i] += idf[t] * f * 2.5 / (f + 1.5 * (.25 + .75 * len(docs[i]) / avg))
    return sorted(s, key=lambda i: (-s[i], i))[:k]
random.seed(0)
hq = [(i, tok(h)) for i, h in enumerate(heads) if len(tok(h)) >= 2]
hq = random.sample(hq, 300)
lq = [(i, random.sample(docs[i], 8)) for i in random.sample(range(N), 200)]
print(f"python {platform.python_version()} chunks={N} avg_chars={sum(map(len,chunks))/N:.0f}")
print("note: heading queries hit if the source chunk is retrieved (several chunks can share a heading text; exact index is required)")
KS = [1, 3, 5, 10, 20, 50]
res = {}
for name, qs in [("heading", hq), ("8-token", lq)]:
    tops = [(i, top(q, 50)) for i, q in qs]
    res[name] = [sum(i in t[:k] for i, t in tops) / len(qs) for k in KS]
print(f"{'k':>3} {'recall heading':>15} {'recall 8-token':>15} {'ctx chars (mean of top-k)':>26}")
allt = [top(q, 50) for _, q in hq]
for j, k in enumerate(KS):
    ctx = sum(sum(len(chunks[i]) for i in t[:k]) for t in allt) / len(allt)
    print(f"{k:>3} {res['heading'][j]:>15.3f} {res['8-token'][j]:>15.3f} {ctx:>26.0f}")
