import json, sys, collections
sys.path.insert(0, "/tmp/claude-1000/-var-www-html-peta/310517d2-8f28-442b-9907-0e3560add2cb/scratchpad")
from vrest02_decisions import DEC

IN = "/var/www/html/peta/storage/app/propertylab-catalogue-match/review/v_rest_02_in.jsonl"
OUT = "/var/www/html/peta/storage/app/propertylab-catalogue-match/review/v_rest_02_out.jsonl"
rows = [json.loads(l) for l in open(IN)]
errors = []
ids = [r["case"] for r in rows]
missing = [c for c in ids if c not in DEC]
extra = [c for c in DEC if c not in ids]
if missing: errors.append(f"missing {missing}")
if extra: errors.append(f"extra {extra}")
out_lines = []
for r in rows:
    c = r["case"]
    if c not in DEC:
        continue
    verdict, cand, conf, rel, reason, web = DEC[c]
    ks = [x["k"] for x in r["catalogue_candidates"]]
    if verdict not in ("SAME", "PART_OF", "DIFFERENT", "UNSURE"): errors.append(f"{c} bad verdict")
    if cand is not None and cand not in ks: errors.append(f"{c} cand {cand} not in {ks}")
    if verdict in ("SAME", "PART_OF") and cand is None: errors.append(f"{c} needs cand")
    if verdict == "DIFFERENT" and cand is not None: errors.append(f"{c} DIFFERENT with cand")
    if verdict == "PART_OF" and rel not in ("R_in_C", "C_in_R"): errors.append(f"{c} PART_OF needs relation")
    if verdict != "PART_OF" and rel is not None: errors.append(f"{c} relation only for PART_OF")
    if not (isinstance(conf, int) and 0 <= conf <= 100): errors.append(f"{c} bad conf")
    nw = len(reason.split())
    if nw > 20: errors.append(f"{c} reason {nw} words")
    out_lines.append(json.dumps({"case": c, "verdict": verdict, "cand": cand, "confidence_pct": conf,
                                 "relation": rel, "reason": reason, "web": bool(web)}, ensure_ascii=False))
webn = sum(1 for v in DEC.values() if v[5])
if webn > 15: errors.append(f"web cases {webn} > 15")
if errors:
    print("ERRORS:"); print("\n".join(errors)); sys.exit(1)
if "--write" in sys.argv:
    with open(OUT, "w") as f:
        f.write("\n".join(out_lines) + "\n")
    print("written", len(out_lines))
cnt = collections.Counter(v[0] for v in DEC.values())
print("counts", dict(cnt), "total", sum(cnt.values()))
print(">=90:", sum(1 for v in DEC.values() if v[2] >= 90), "web:", webn)
print(">=90 by verdict:", dict(collections.Counter(v[0] for v in DEC.values() if v[2] >= 90)))
if "--show" in sys.argv:
    for r in rows:
        v = DEC[r["case"]]
        cn = next((x["name"] for x in r["catalogue_candidates"] if x["k"] == v[1]), None)
        print(f"{r['case']} {v[0]:9} k{v[1]} {v[2]:3} {str(v[3]):6} | R={r['realtycheck']['name']} | C={cn}")
