"""RAG request logging: one JSON line per request. Measures (1) log overhead per request, (2) bytes per line,
(3) which questions the logs can answer. BM25 over FastAPI docs; the 'LLM' is a stub (no network), so only
retrieval + logging cost is measured. Run from this directory after experiments/fetch_corpus.sh."""
import re, glob, math, collections, json, time, uuid, hashlib, os, random, statistics as st, contextvars, sys
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
import fastapi, httpx

TOK = re.compile(r"[a-z0-9_]+")
def toks(s): return TOK.findall(s.lower())
chunks = []  # (chunk_id, doc, text)
for p in sorted(glob.glob('../corpus/*.md')):
    t = open(p, encoding='utf-8').read(); doc = os.path.basename(p)
    for j, para in enumerate(x for x in re.split(r"\n\s*\n", t) if len(x.strip()) > 40):
        chunks.append((f"{doc}#{j}", doc, para))
tf = [collections.Counter(toks(c[2])) for c in chunks]
N = len(chunks); df = collections.Counter(t for c in tf for t in c)
L = [sum(c.values()) for c in tf]; avg = sum(L) / N
idf = {t: math.log(1 + (N - n + .5) / (n + .5)) for t, n in df.items()}
inv = collections.defaultdict(list)
for i, c in enumerate(tf):
    for t, f in c.items(): inv[t].append((i, f))
def bm25(q, k=5):
    sc = collections.defaultdict(float)
    for t in set(toks(q)):
        for i, f in inv.get(t, ()):
            sc[i] += idf[t] * f * 2.5 / (f + 1.5 * (.25 + .75 * L[i] / avg))
    return sorted(sc.items(), key=lambda x: -x[1])[:k]
print(f"chunks={N} fastapi={fastapi.__version__} httpx={httpx.__version__}")

# ---------- logging layer ----------
ctx = contextvars.ContextVar("rec", default=None)
class Sink:
    def __init__(self, path): self.f = open(path, "w", buffering=1 << 16)
    def write(self, rec): self.f.write(json.dumps(rec, separators=(",", ":")) + "\n")
    def close(self): self.f.close()

def build_app(sink, mode):
    """mode: 'off' | 'ids' (chunk ids + scores) | 'text' (ids + full chunk text + prompt)"""
    app = FastAPI()
    @app.middleware("http")
    async def log_mw(request: Request, call_next):
        if mode == "off": return await call_next(request)
        rec = {"ts": time.time(), "request_id": request.headers.get("x-request-id") or uuid.uuid4().hex[:12],
               "route": request.url.path, "index_version": "fastapi-docs-2026-12-03", "stages_ms": {}}
        tok = ctx.set(rec); t0 = time.perf_counter()
        try:
            resp = await call_next(request); rec["status"] = resp.status_code
            return resp
        except Exception as e:
            rec["status"] = 500; rec["error"] = type(e).__name__; raise
        finally:
            rec["latency_ms"] = round((time.perf_counter() - t0) * 1000, 3)
            sink.write(rec); ctx.reset(tok)
    @app.get("/ask")
    async def ask(q: str):
        rec = ctx.get()
        t = time.perf_counter(); hits = bm25(q); rt = (time.perf_counter() - t) * 1000
        top = hits[0][1] if hits else 0.0
        refused = top < 8.0  # BM25 score gate (illustrative)
        if rec is not None:
            rec["query_sha1"] = hashlib.sha1(q.encode()).hexdigest()[:10]; rec["query_len"] = len(q)
            rec["stages_ms"]["retrieve"] = round(rt, 3)
            rec["retrieval"] = {"k": 5, "n_hits": len(hits), "top1": round(top, 2),
                                "scores": [round(s, 2) for _, s in hits],
                                "chunk_ids": [chunks[i][0] for i, _ in hits]}
            if mode == "text":
                rec["query"] = q; rec["retrieval"]["texts"] = [chunks[i][2] for i, _ in hits]
            rec["outcome"] = "refused_low_score" if refused else "answered"
        if refused: return {"answer": "I don't know."}
        prompt = "\n\n".join(chunks[i][2] for i, _ in hits) + "\n\nQ: " + q
        if rec is not None:
            rec["generation"] = {"model": "stub", "prompt_chars": len(prompt), "completion_chars": 40}
            if mode == "text": rec["generation"]["prompt"] = prompt
        return {"answer": "stub answer"}
    return app

queries_ans = ["How do I set a cookie on the response?", "How to declare query parameter validation with Query",
 "How do I use dependency injection with yield", "What is a path parameter in FastAPI", "How do I add CORS middleware",
 "How to run background tasks after returning a response", "How do I handle file uploads", "How to use OAuth2 with JWT tokens",
 "How do I test FastAPI with TestClient", "How to stream a response", "How do I deploy FastAPI with Docker",
 "How to use lifespan events for startup and shutdown", "How to return a custom status code", "How do I declare request body with Pydantic model",
 "How do I serve static files"]
queries_un = ["How do I boil an egg", "Who won the football world cup", "Terraform module for kubernetes", "gRPC streaming with protobuf",
 "How do tides work", "Selenium browser automation", "Prometheus histogram buckets", "best pasta recipe"]
random.seed(0)
workload = [random.choice(queries_ans) if random.random() < .8 else random.choice(queries_un) for _ in range(2000)]

res = {}
for mode in ["off", "ids", "text"]:
    sink = Sink(f"requests_{mode}.jsonl"); c = TestClient(build_app(sink, mode))
    for q in workload[:100]: c.get("/ask", params={"q": q})  # warmup
    sink.close(); sink = Sink(f"requests_{mode}.jsonl"); c = TestClient(build_app(sink, mode))
    lat = []
    for q in workload:
        t = time.perf_counter(); c.get("/ask", params={"q": q}); lat.append((time.perf_counter() - t) * 1000)
    sink.close(); res[mode] = lat
    size = os.path.getsize(f"requests_{mode}.jsonl")
    print(f"mode={mode:5s} n={len(lat)} median_ms={st.median(lat):.3f} p95_ms={sorted(lat)[int(.95*len(lat))]:.3f} mean_ms={st.mean(lat):.3f} log_bytes={size} bytes_per_line={size/len(lat):.0f}" if mode != "off" else
          f"mode={mode:5s} n={len(lat)} median_ms={st.median(lat):.3f} p95_ms={sorted(lat)[int(.95*len(lat))]:.3f} mean_ms={st.mean(lat):.3f}")
for m in ("ids", "text"):
    print(f"overhead {m} vs off: median +{st.median(res[m]) - st.median(res['off']):.3f} ms, mean +{st.mean(res[m]) - st.mean(res['off']):.3f} ms")

# ---------- questions answered from the ids-mode log ----------
rows = [json.loads(l) for l in open("requests_ids.jsonl")]
print("\n--- log analysis (requests_ids.jsonl) ---")
print("rows", len(rows), "fields:", sorted(rows[0].keys()))
oc = collections.Counter(r["outcome"] for r in rows); print("outcomes", dict(oc))
print(f"refusal rate {oc['refused_low_score']/len(rows):.3f}")
for o in oc:
    v = [r["retrieval"]["top1"] for r in rows if r["outcome"] == o]
    print(f"top1 score {o}: median {st.median(v):.2f} min {min(v):.2f} max {max(v):.2f}")
ret = sorted(r["stages_ms"]["retrieve"] for r in rows)
print(f"retrieve_ms p50 {ret[len(ret)//2]:.3f} p95 {ret[int(.95*len(ret))]:.3f} p99 {ret[int(.99*len(ret))]:.3f} max {ret[-1]:.3f}")
print(f"retrieve share of request latency (median of ratio): {st.median(r['stages_ms']['retrieve']/r['latency_ms'] for r in rows):.2f}")
docs = collections.Counter(c.split('#')[0] for r in rows if r["outcome"] == "answered" for c in r["retrieval"]["chunk_ids"][:1])
print("top-1 docs among answered:", docs.most_common(5))
q = collections.Counter(r["query_sha1"] for r in rows if r["outcome"] == "refused_low_score")
print("distinct refused queries", len(q), "top repeated:", q.most_common(3))
print("distinct queries overall", len({r['query_sha1'] for r in rows}))
