import json, glob, sys
base = "/tmp/claude-1000/-var-www-html-peta/310517d2-8f28-442b-9907-0e3560add2cb/scratchpad/"
inp = "/var/www/html/peta/storage/app/propertylab-catalogue-match/review/r2_batch_03_in.jsonl"
out = "/var/www/html/peta/storage/app/propertylab-catalogue-match/review/r2_batch_03_out.jsonl"

def parse(path):
    d = {}
    for line in open(path):
        line = line.rstrip("\n")
        if not line.strip():
            continue
        parts = line.split("|")
        assert len(parts) in (5, 6), (path, line)
        case, verdict, cand, conf, reason = parts[:5]
        web = len(parts) == 6 and parts[5] == "web"
        d[case] = dict(verdict=verdict, cand=None if cand == "null" else int(cand), confidence=conf, reason=reason, web=web)
    return d

dec = {}
for p in sorted(glob.glob(base + "r2b03_dec_*.txt")):
    part = parse(p)
    dup = set(part) & set(dec)
    assert not dup, dup
    dec.update(part)
ov = parse(base + "r2b03_overrides.txt")
for k, v in ov.items():
    assert k in dec, k
    dec[k] = v

cases = [json.loads(l) for l in open(inp)]
errors = []
lines = []
seen = set()
for c in cases:
    cid = c["case"]
    if cid not in dec:
        errors.append(f"missing {cid}"); continue
    v = dec[cid]
    ks = {x["k"] for x in c["catalogue_candidates"]}
    if v["verdict"] not in ("SAME", "PART_OF", "DIFFERENT", "UNSURE"): errors.append(f"bad verdict {cid}")
    if v["confidence"] not in ("high", "medium", "low"): errors.append(f"bad conf {cid}")
    if v["verdict"] in ("SAME", "PART_OF") and v["cand"] is None: errors.append(f"null cand for {v['verdict']} {cid}")
    if v["verdict"] == "DIFFERENT" and v["cand"] is not None: errors.append(f"DIFFERENT with cand {cid}")
    if v["cand"] is not None and v["cand"] not in ks: errors.append(f"cand {v['cand']} not in {ks} for {cid}")
    if len(v["reason"].split()) > 20: errors.append(f"reason too long ({len(v['reason'].split())}) {cid}: {v['reason']}")
    if cid in seen: errors.append(f"dup {cid}")
    seen.add(cid)
    lines.append(json.dumps({"case": cid, "verdict": v["verdict"], "cand": v["cand"], "confidence": v["confidence"], "reason": v["reason"], "web": v["web"]}, ensure_ascii=False))
extra = set(dec) - {c["case"] for c in cases}
if extra: errors.append(f"extra decisions {extra}")
if errors:
    print("\n".join(errors)); sys.exit(1)
if len(sys.argv) > 1 and sys.argv[1] == "write":
    with open(out, "w") as f:
        f.write("\n".join(lines) + "\n")
    print("written", len(lines))
else:
    print("ok", len(lines))
