"""Score your own retrieval the way lesson 2.2 does: how often the right passage is in the top k, and how often an
outdated or look-alike passage is.

    python3 stale_at_k.py --example                    # writes naive.jsonl and hybrid.jsonl, to see the format
    python3 stale_at_k.py naive.jsonl hybrid.jsonl     # one file per retrieval method, compared side by side

Each line of a file is one question your retriever answered:
    {"question": "...", "relevant": ["doc-12#3"], "outdated": ["doc-07#3"], "retrieved": ["doc-07#3", "doc-12#3", ...]}
relevant: the passages that answer it. outdated: old versions or look-alikes that must not be used (may be empty).
retrieved: your retriever's ranked ids for that question. Use the same questions in every file.

recall@k: share of questions with a relevant passage in the top k. MRR: mean of 1 / rank of the first relevant
passage, over the full ranked list. stale@k (neg@k in the lesson): among the questions that have an outdated
passage to find, the share with one in the top k.
Standard library only. Python 3.9 or later.
"""
# From lesson 2.2 of Cohorte's Context Architecture (cohorte.co/context-architecture).
import argparse
import json
import sys
import textwrap
from pathlib import Path

EXAMPLE = [   # three questions; the two files differ only in how each method ranked them
    ("What is the return window for opened items?", ["policy-2026#returns"], ["policy-2024#returns"],
     ["policy-2024#returns", "faq#returns", "policy-2026#returns"], ["policy-2026#returns", "faq#returns"]),
    ("Who approves net-60 payment terms?", ["finance-handbook#terms"], [],
     ["contract-northgate#7", "finance-handbook#terms"], ["finance-handbook#terms", "contract-northgate#7"]),
    ("What is the liability cap in the Northgate contract?", ["contract-northgate#12"], ["contract-northline#12"],
     ["contract-northline#12", "contract-northgate#12"], ["contract-northgate#12", "faq#contracts"]),
]


def load(path):
    rows = []
    with open(path, encoding="utf-8") as f:
        for i, line in enumerate(f, 1):
            if not line.strip():
                continue
            try:
                r = json.loads(line)
                rows.append((r["question"], set(r["relevant"]), set(r.get("outdated") or []), list(r["retrieved"])))
            except (json.JSONDecodeError, KeyError, TypeError) as e:
                sys.exit(f"{path}, line {i}: needs question, relevant and retrieved ({type(e).__name__}: {e}).")
    if not rows:
        sys.exit(f"No questions in {path}.")
    return rows


def score(rows, k):
    hit1 = hitk = rr = stale = with_outdated = 0
    for _, relevant, outdated, retrieved in rows:
        ranks = [i for i, d in enumerate(retrieved, 1) if d in relevant]
        hit1 += bool(ranks) and ranks[0] == 1
        hitk += bool(ranks) and ranks[0] <= k
        rr += 1 / ranks[0] if ranks else 0
        if outdated:
            with_outdated += 1
            stale += any(d in outdated for d in retrieved[:k])
    n = len(rows)
    return {"n": n, "r1": hit1 / n, "rk": hitk / n, "mrr": rr / n, "with_outdated": with_outdated,
            "stale": stale / with_outdated if with_outdated else None}


def write_example():
    names = ("naive.jsonl", "hybrid.jsonl")
    if any(Path(n).exists() for n in names):
        sys.exit("naive.jsonl or hybrid.jsonl already exists here; run --example in an empty folder.")
    for col, name in ((3, names[0]), (4, names[1])):
        Path(name).write_text("".join(json.dumps({"question": q[0], "relevant": q[1], "outdated": q[2],
                                                  "retrieved": q[col]}) + "\n" for q in EXAMPLE))
    print("wrote naive.jsonl and hybrid.jsonl")


def main():
    ap = argparse.ArgumentParser(description="recall@k, MRR and stale@k for your retrieval results.")
    ap.add_argument("files", nargs="*", help="one JSONL file per retrieval method")
    ap.add_argument("-k", type=int, default=5, help="cut-off (default 5)")
    ap.add_argument("--example", action="store_true", help="write naive.jsonl and hybrid.jsonl, then stop")
    a = ap.parse_args()
    if a.k < 1:
        ap.error("-k must be 1 or more")
    if a.example:
        return write_example()
    if not a.files:
        ap.error("give one JSONL file per method, or --example")
    runs = [(Path(f).stem, load(f)) for f in a.files]
    if len({frozenset(q for q, *_ in rows) for _, rows in runs}) > 1:
        print("Warning: the files don't hold the same questions; compare like with like.")
    w = max(8, max(len(name) for name, _ in runs) + 2)
    cols = [("recall@1", "r1")] + ([(f"recall@{a.k}", "rk")] if a.k > 1 else [])
    print(f"{'method':<{w}}{'n':>5}" + "".join(f"{c:>10}" for c, _ in cols) + f"{'MRR':>7}{f'stale@{a.k}':>10}")
    for name, rows in runs:
        s = score(rows, a.k)
        stale = f"{s['stale']:.0%} of {s['with_outdated']}" if s["stale"] is not None else "n/a"
        print(f"{name:<{w}}{s['n']:>5}" + "".join(f"{s[key]:>10.0%}" for _, key in cols) + f"{s['mrr']:>7.2f}{stale:>10}")
    print(textwrap.fill(f"stale@{a.k} counts only the questions that have an outdated or look-alike passage "
                        f"to find: the number after 'of'.", 72))


if __name__ == "__main__":
    main()
