#!/usr/bin/env python3
"""Score out/invoices.json against pilot-012 golden data.

Fields scored per invoice: invoice_id, vendor_name, total (15 invoices x 3 = 45 points).
vendor_name matches case-insensitively after whitespace collapse; total within 0.01.
Usage: score_task3.py <repo_root> [golden.json]
"""
import json
import re
import sys

GOLDEN_DEFAULT = "<pilot-012>/dataset/golden.json"  # NOTE: this path is scrubbed and not present in this evidence bundle.
# The scored results are already in harness/results/*.json; this script is published
# so you can read the scoring LOGIC, not to be re-run standalone against this bundle.

repo = sys.argv[1]
golden_path = sys.argv[2] if len(sys.argv) > 2 else GOLDEN_DEFAULT
golden = {g["invoice_id"]: g for g in json.load(open(golden_path))}

def golden_total(g):
    if "total" in g:
        return g["total"]
    return round(sum(li["amount"] for li in g["line_items"]), 2)

norm = lambda s: re.sub(r"\s+", " ", (s or "").strip().lower())

try:
    got = json.load(open(f"{repo}/out/invoices.json"))
except Exception as e:
    print(json.dumps({"score": 0, "max": len(golden) * 3, "error": str(e)}))
    sys.exit(0)

by_id = {r.get("invoice_id"): r for r in got if isinstance(r, dict)}
score, detail = 0, {}
for inv_id, g in golden.items():
    r = by_id.get(inv_id)
    pts = 0
    if r is not None:
        pts += 1  # id found
        if norm(r.get("vendor_name")) == norm(g["vendor_name"]):
            pts += 1
        try:
            if abs(float(r.get("total")) - golden_total(g)) <= 0.01:
                pts += 1
        except (TypeError, ValueError):
            pass
    detail[inv_id] = pts
    score += pts
print(json.dumps({"score": score, "max": len(golden) * 3, "detail": detail}))
