"""Read the two models' cached answers: the reply parser, the cache reader and the replay check.

Usage: python3 -I -B tools/review.py --replay      (cache only: no key, no network)

Every chart was sent once to each model with the fixed prompt below and the chart PNG, and every reply was stored in
cache/<model id>.jsonl, one line per call: the chart id, the image's sha256, the raw reply, the parsed answer, the
usage figures and, for a failed call, the error. A failed call (error, refusal or unparsable reply) was re-run once
as a declared re-run, then the chart would have been excluded and counted; none was. The code that made the calls
names the two model routes and is kept in the source repository, outside this download, so the calls cannot be re-run
from the download alone; everything after them can.
"""
import argparse
import json
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
MODELS = ("claude-sonnet-5-5", "gpt-6.1-sol")
PROMPT = ("This image is a chart that is about to be published. Check it for two problems only.\n"
          "1. Overlapping text: a piece of text (title, axis label, tick label, legend entry) that overlaps another piece of text.\n"
          "2. Clipped text: a piece of text that is cut off by the edge of the image.\n"
          "Reply with JSON only, no other text, in this form:\n"
          "{\"overlap\": true or false, \"overlap_where\": \"which text, or empty\", \"clipped\": true or false, "
          "\"clipped_where\": \"which text, or empty\"}")


def parse(text):
    """The last {...} block in the reply, with boolean overlap and clipped; None if there is none."""
    if not text:
        return None
    for block in reversed(re.findall(r"\{[^{}]*\}", text, re.S)):
        try:
            d = json.loads(block)
        except json.JSONDecodeError:
            continue
        if isinstance(d.get("overlap"), bool) and isinstance(d.get("clipped"), bool):
            return d
    return None


def load_cache(model):
    p = ROOT / "cache" / f"{model}.jsonl"
    rows = []
    if p.exists():
        rows = [json.loads(x) for x in p.read_text(encoding="utf-8").splitlines() if x.strip()]
    return p, rows


def todo(rows, ids):
    """Charts that would still need a call: no answer yet and fewer than two attempts."""
    done = {}
    for r in rows:
        done.setdefault(r["chart"], []).append(r)
    out = []
    for c in ids:
        prior = done.get(c, [])
        if any(r["error"] is None for r in prior) or len(prior) >= 2:
            continue
        out.append(c)
    return out


def chart_ids():
    return [json.loads(x)["chart"] for x in (ROOT / "results" / "geometry.jsonl").read_text(encoding="utf-8").splitlines()
            if x.strip()]


def replay():
    """Every chart answered, every stored parse equal to a fresh parse of the stored reply, image hashes matching the
    measured charts. Returns a list of problems."""
    geo = {json.loads(x)["chart"]: json.loads(x)["png_sha256"]
           for x in (ROOT / "results" / "geometry.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()}
    problems = []
    for model in MODELS:
        _, rows = load_cache(model)
        left = todo(rows, list(geo))
        if left:
            problems.append(f"{model}: {len(left)} charts unanswered")
        for r in rows:
            if r["chart"] not in geo:
                problems.append(f"{model}: unknown chart {r['chart']}")
                continue
            if r["image_sha256"] != geo[r["chart"]]:
                problems.append(f"{model}: {r['chart']} image hash differs from the measured chart")
            if r["error"] is None and parse(r["raw"]) != r["parsed"]:
                problems.append(f"{model}: {r['chart']} stored parse differs from a fresh parse")
            if r["error"] == "unparsable" and parse(r["raw"]) is not None:
                problems.append(f"{model}: {r['chart']} marked unparsable but parses")
    return problems


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--replay", action="store_true", required=True)
    ap.parse_args()
    problems = replay()
    for m in MODELS:
        _, rows = load_cache(m)
        print(f"{m}: {len({r['chart'] for r in rows if r['error'] is None})} charts answered, {len(rows)} calls stored")
    for p in problems[:20]:
        print(p)
    print(f"VERDICT: {'PASS' if not problems else 'FAIL'} ({len(problems)} problems)")


if __name__ == "__main__":
    main()
