#!/usr/bin/env python3
"""Invoice OCR test harness for accounts payable: generate, extract, score.

  python3 ap_ocr_test.py generate DIR --seed 2027 --per-cell 19
  python3 ap_ocr_test.py run DIR [--engine baseline|vendor] [--prep none|cleanup] [--tag _plain]
  python3 ap_ocr_test.py score DIR [--tag _plain] [--conf 75]
Writes DIR/extractions<tag>.json, DIR/results<tag>.csv (one row per invoice) and DIR/results<tag>.json.

Needs Python 3.9+, reportlab, pymupdf, pillow, numpy and tesseract 5 on PATH.
The extractor is a plain baseline written for this test (regex plus word
positions). It is not any vendor's product. To test a vendor, fill in
vendor_adapter() below; scoring does not change.
"""
import argparse, csv, datetime, difflib, json, math, os, random, re, subprocess, sys, time
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

TEMPLATES = ["A", "B", "C", "D"]
TIERS = ["digital", "clean", "mild", "low"]
DPI = {"clean": 200, "mild": 200, "low": 100}
DEFECTS = ["wrong_total", "tax_mismatch", "missing_po", "duplicate"]
HEADER = ["vendor", "invoice_number", "date", "currency", "subtotal", "tax", "total", "po"]
RATES = {"USD": [5, 7, 8, 10], "EUR": [19, 21], "GBP": [20]}
MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
CONF_MIN = 75          # low-confidence rule, fixed on the development set
TOL = Decimal("0.01")  # reconcile tolerance
REVIEW_MIN, REWORK_MIN, RATE_PER_HOUR, PAGE_PRICE = 4, 15, 30, Decimal("0.02")  # hypothetical cost inputs


def q2(x):
    return Decimal(x).quantize(Decimal("0.01"), ROUND_HALF_UP)


# ------------------------------------------------------------------ generate
ADJ = ["Thermal", "Copper", "Steel", "Laminated", "Recycled", "Rapid", "Heavy duty", "Standard", "Compact", "Industrial"]
NOUN = ["paper rolls", "pipe fittings", "label ribbon", "safety gloves", "pallet wrap", "bearing set", "cable ties",
        "filter cartridges", "hex bolts", "storage bins", "work lamps", "drill bits"]
FIRST = ["Northwind", "Alder", "Birch", "Cobalt", "Dunmore", "Everly", "Fairhaven", "Granite", "Harlow", "Ironbridge",
         "Juniper", "Kestrel", "Larkspur", "Mercer", "Norfolk", "Oakridge", "Pinecrest", "Quillon", "Ridgeway", "Stonebrook"]
LAST = ["Supply Co.", "Logistics Ltd", "Industrial GmbH", "Office Goods", "Packaging Inc.", "Tools & Parts", "Freight Services"]
STREET = ["Mill Road", "Station Lane", "Harbour Street", "Foundry Way", "Elm Avenue", "Canal Row"]
CUSTOMER = ["Marlowe Distribution Ltd", "Tern Hospitality Group", "Calder Clinics LLC", "Pike and Sons Builders"]


def fm(v, cur):
    s = f"{Decimal(v):,.2f}"
    return s.translate(str.maketrans(",.", ".,")) if cur == "EUR" else s


def fd(iso, style):
    y, m, d = map(int, iso.split("-"))
    return {"iso": iso, "dmy": f"{d} {MON[m - 1]} {y}", "dot": f"{d:02d}.{m:02d}.{y}", "mdy": f"{MON[m - 1]} {d}, {y}"}[style]


def new_invoice(rng, used):
    cur = rng.choice(["USD", "USD", "EUR", "GBP"])
    rate = rng.choice(RATES[cur])
    descs = rng.sample([f"{a} {b}" for a in ADJ for b in NOUN], rng.randint(3, 14))
    lines = []
    for d in descs:
        qty, unit = rng.randint(1, 40), q2(Decimal(rng.randint(150, 45000)) / 100)
        lines.append({"desc": d, "qty": qty, "unit": str(unit), "amount": str(q2(qty * unit))})
    sub = sum(Decimal(l["amount"]) for l in lines)
    tax = q2(sub * rate / 100)
    while True:
        no = f"{rng.choice(['INV', 'BC', 'SI', 'AP'])}-{rng.randint(10000, 99999)}"
        if no not in used:
            used.add(no)
            break
    return {"vendor": f"{rng.choice(FIRST)} {rng.choice(LAST)}", "invoice_number": no,
            "date": str(datetime.date(2026, rng.randint(1, 10), rng.randint(1, 28))),
            "po": f"PO-{rng.randint(10000, 99999)}", "currency": cur, "tax_rate": rate, "lines": lines,
            "subtotal": str(q2(sub)), "tax": str(tax), "total": str(q2(sub + tax)),
            "addr": f"{rng.randint(2, 480)} {rng.choice(STREET)}", "customer": rng.choice(CUSTOMER)}


def T(c, x, y, s, font="Helvetica", size=10, right=False):
    c.setFont(font, size)
    (c.drawRightString if right else c.drawString)(x, y, s)


def draw(c, t):
    from reportlab.lib.colors import Color
    cur, tp = t["currency"], t["template"]
    f = lambda v: fm(v, cur)
    due = str(datetime.date.fromisoformat(t["date"]) + datetime.timedelta(30))
    lines, rate = t["lines"], t["tax_rate"]
    if tp == "A":  # bordered line item table, labels on the right
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 16); T(c, 562, 750, "INVOICE", "Helvetica-Bold", 22, True)
        T(c, 50, 736, t["addr"], size=9)
        meta = [("Invoice No:", t["invoice_number"]), ("Date:", fd(t["date"], "iso")), ("Due:", fd(due, "iso"))]
        if t["po"]: meta.append(("PO Number:", t["po"]))
        meta.append(("Currency:", cur))
        for i, (k, v) in enumerate(meta): T(c, 380, 715 - 14 * i, k); T(c, 465, 715 - 14 * i, v)
        T(c, 50, 700, "Bill to:"); T(c, 50, 686, t["customer"])
        edges, top = [50, 300, 350, 450, 562], 630
        for j, h in enumerate(["Description", "Qty", "Unit price", "Amount"]):
            c.rect(edges[j], top - 20, edges[j + 1] - edges[j], 20); T(c, edges[j + 1] - 5 if j else 55, top - 14, h, "Helvetica-Bold", 10, bool(j))
        for r, l in enumerate(lines):
            y0 = top - 20 * (r + 2)
            for j, v in enumerate([l["desc"], str(l["qty"]), f(l["unit"]), f(l["amount"])]):
                c.rect(edges[j], y0, edges[j + 1] - edges[j], 20); T(c, edges[j + 1] - 5 if j else 55, y0 + 6, v, right=bool(j))
        y = top - 20 * (len(lines) + 2) - 22
        for lab, v, bold in [("Subtotal", t["subtotal"], 0), (f"Tax {rate}%", t["tax"], 0), ("Total due", t["total"], 1)]:
            fn = "Helvetica-Bold" if bold else "Helvetica"
            T(c, 500, y, lab, fn, 10, True); T(c, 557, y, f(v), fn, 10, True); y -= 16
        T(c, 50, 60, "Payment terms: Net 30", size=9)
    elif tp == "B":  # no borders, Times, labels glued to values, left aligned columns
        T(c, 50, 750, t["vendor"], "Times-Bold", 18); T(c, 50, 736, t["addr"], "Times-Roman", 10)
        T(c, 50, 706, f"Tax Invoice #{t['invoice_number']}", "Times-Roman", 12)
        T(c, 50, 690, f"Issued: {fd(t['date'], 'dmy')}", "Times-Roman", 12)
        yy = 674
        if t["po"]: T(c, 50, yy, f"Customer order ref: {t['po']}", "Times-Roman", 12); yy -= 16
        T(c, 50, yy, f"Currency: {cur}", "Times-Roman", 12)
        xs, top = [50, 330, 400, 470], 610
        for x, h in zip(xs, ["Item", "Price", "Quantity", "Line total"]): T(c, x, top, h, "Times-Bold", 11)
        for r, l in enumerate(lines):
            for x, v in zip(xs, [l["desc"], f(l["unit"]), str(l["qty"]), f(l["amount"])]): T(c, x, top - 18 * (r + 1), v, "Times-Roman", 11)
        y = top - 18 * (len(lines) + 1) - 24
        for lab, v in [("Net", t["subtotal"]), (f"VAT {rate}%", t["tax"]), ("Amount payable", t["total"])]:
            T(c, 380, y, lab, "Times-Roman", 11); T(c, 540, y, f(v), "Times-Roman", 11, True); y -= 16
        T(c, 50, 60, "Payment terms: net 30", "Times-Roman", 10)
    elif tp == "C":  # two column header, ruled rows only
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 14); T(c, 50, 736, t["addr"], size=9); T(c, 50, 724, "Customer accounts", size=9)
        T(c, 562, 752, "INVOICE", "Helvetica-Bold", 24, True)
        meta = [("Invoice number:", t["invoice_number"]), ("Invoice date:", fd(t["date"], "dot")), ("Payment due:", fd(due, "dot"))]
        if t["po"]: meta.append(("Purchase order:", t["po"]))
        meta.append(("Currency:", cur))
        for i, (k, v) in enumerate(meta): T(c, 350, 724 - 14 * i, k); T(c, 450, 724 - 14 * i, v)
        T(c, 50, 660, "Bill to", "Helvetica-Bold", 10); T(c, 50, 646, t["customer"])
        c.setFillColor(Color(0.88, 0.88, 0.88)); c.rect(50, 584, 512, 20, fill=1, stroke=0); c.setFillColor(Color(0, 0, 0))
        for x, h, rt in [(55, "Description", 0), (340, "Qty", 1), (430, "Rate", 1), (557, "Amount", 1)]: T(c, x, 590, h, "Helvetica-Bold", 10, bool(rt))
        for r, l in enumerate(lines):
            y0 = 584 - 20 * (r + 1)
            c.line(50, y0, 562, y0)
            T(c, 55, y0 + 6, l["desc"]); T(c, 340, y0 + 6, str(l["qty"]), right=True); T(c, 430, y0 + 6, f(l["unit"]), right=True); T(c, 557, y0 + 6, f(l["amount"]), right=True)
        y = 584 - 20 * (len(lines) + 1) - 22
        for lab, v, bold in [("Subtotal", t["subtotal"], 0), (f"Sales tax ({rate}%)", t["tax"], 0), ("Balance due", t["total"], 1)]:
            fn = "Helvetica-Bold" if bold else "Helvetica"
            T(c, 500, y, lab, fn, 10, True); T(c, 557, y, f(v), fn, 10, True); y -= 16
    else:  # D: label above value strip, quantity first, summary on page 2
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 16); T(c, 562, 750, "Invoice", "Helvetica-Bold", 20, True); T(c, 50, 736, t["addr"], size=9)
        cells = [("Invoice no.", t["invoice_number"]), ("Date", fd(t["date"], "mdy")), ("PO no.", t["po"] or "n/a"), ("Due", fd(due, "mdy")), ("Currency", cur)]
        for i, (k, v) in enumerate(cells): T(c, 50 + 105 * i, 690, k, size=8); T(c, 50 + 105 * i, 676, v)
        T(c, 50, 650, "Bill to: " + t["customer"])
        c.setFillColor(Color(0.88, 0.88, 0.88)); c.rect(50, 604, 512, 20, fill=1, stroke=0); c.setFillColor(Color(0, 0, 0))
        T(c, 55, 610, "Qty", "Helvetica-Bold", 10); T(c, 100, 610, "Description", "Helvetica-Bold", 10)
        T(c, 440, 610, "Unit price", "Helvetica-Bold", 10, True); T(c, 557, 610, "Total", "Helvetica-Bold", 10, True)
        for r, l in enumerate(lines):
            y0 = 610 - 18 * (r + 1)
            T(c, 55, y0, str(l["qty"])); T(c, 100, y0, l["desc"]); T(c, 440, y0, f(l["unit"]), right=True); T(c, 557, y0, f(l["amount"]), right=True)
        T(c, 50, 60, "Totals are on page 2", size=9)
        c.showPage()
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 12); T(c, 562, 750, f"Page 2 of 2", size=9, right=True)
        T(c, 50, 700, "Summary", "Helvetica-Bold", 16)
        y = 670
        for lab, v, bold in [("Subtotal", t["subtotal"], 0), (f"Tax ({rate}%)", t["tax"], 0), ("Total", t["total"], 1)]:
            fn = "Helvetica-Bold" if bold else "Helvetica"
            T(c, 400, y, lab, fn, 11, True); T(c, 520, y, f(v), fn, 11, True); y -= 18
        T(c, 50, 600, "Please pay within 30 days. Bank reference 2026" + t["invoice_number"][-5:], size=9)
    c.showPage()


def degrade(img, tier, nrng, rng):
    import numpy as np
    from PIL import Image, ImageFilter
    if tier == "clean":
        return img, "png", {}
    if tier == "mild":
        ang = rng.choice([-1, 1]) * rng.uniform(1, 3)
        img = img.rotate(ang, resample=Image.BICUBIC, fillcolor=255).filter(ImageFilter.GaussianBlur(0.6))
        sigma, qual = 10, 70
    else:
        ang, img = 0, img.filter(ImageFilter.GaussianBlur(0.5))
        sigma, qual = 12, 55
    a = np.asarray(img, dtype=np.float32) + nrng.normal(0, sigma, (img.height, img.width))
    return Image.fromarray(np.clip(a, 0, 255).astype("uint8")), "jpg", {"quality": qual, "angle": round(ang, 2)}


def generate(a):
    import numpy as np, pymupdf
    from PIL import Image
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    out = Path(a.dir); out.mkdir(parents=True, exist_ok=True)
    rng, nrng, used = random.Random(a.seed), np.random.default_rng(a.seed), set()
    cells = [(tp, ti) for tp in TEMPLATES for ti in TIERS for _ in range(a.per_cell)]
    rng.shuffle(cells)
    n = len(cells)
    k = max(1, round(n * 0.04))  # 4 defect types, about 16 percent seeded in all
    idx = list(range(n)); rng.shuffle(idx)
    defect = {}
    for d, chunk in zip(DEFECTS[:3], [idx[:k], idx[k:2 * k], idx[2 * k:3 * k]]):
        for i in chunk: defect[i] = d
    inv = [dict(new_invoice(rng, used), template=tp, tier=ti, defect="none", dup_of=None) for tp, ti in cells]
    for i, d in defect.items():
        t = inv[i]; t["defect"] = d
        if d == "missing_po": t["po"] = None
        if d == "wrong_total": t["total"] = str(q2(Decimal(t["total"]) + rng.choice([-1, 1]) * Decimal(rng.randint(500, 50000)) / 100))
        if d == "tax_mismatch":
            t["tax"] = str(max(Decimal("0"), q2(Decimal(t["tax"]) + rng.choice([1, 1, -1]) * Decimal(rng.randint(100, 2500)) / 100)))
            t["total"] = str(q2(Decimal(t["subtotal"]) + Decimal(t["tax"])))
    free = [i for i in idx[3 * k:]]
    dups, locked = 0, set()  # locked: invoices already used as the original of a duplicate
    for i in sorted(free, key=lambda _: rng.random()):
        if dups == k: break
        if i < 20 or i in locked or inv[i]["defect"] != "none": continue
        pool = [j for j in range(i) if inv[j]["template"] == inv[i]["template"] and inv[j]["defect"] == "none"]
        if not pool: continue
        j = rng.choice(pool); locked.add(j)
        keep = {x: inv[i][x] for x in ("template", "tier")}
        inv[i] = dict(inv[j], **keep, defect="duplicate", dup_of=f"inv{j:03d}")
        dups += 1
    order = []
    for i, t in enumerate(inv):
        t["id"] = f"inv{i:03d}"
        t["pages"] = 2 if t["template"] == "D" else 1
        pdf = out / f"{t['id']}.pdf"
        c = canvas.Canvas(str(pdf), pagesize=letter); draw(c, t); c.save()
        if t["tier"] != "digital":
            for p, pg in enumerate(pymupdf.open(str(pdf))):
                pix = pg.get_pixmap(dpi=DPI[t["tier"]], colorspace=pymupdf.csGRAY)
                img, ext, info = degrade(Image.frombytes("L", (pix.width, pix.height), pix.samples), t["tier"], nrng, rng)
                img.save(out / f"{t['id']}_p{p + 1}.{ext}", dpi=(DPI[t["tier"]],) * 2, **({"quality": info["quality"]} if ext == "jpg" else {}))
        (out / f"{t['id']}.json").write_text(json.dumps(t, indent=1))
        order.append(t["id"])
    (out / "manifest.json").write_text(json.dumps(order))
    print(f"{n} invoices in {out}; defects:", {d: sum(1 for t in inv if t['defect'] == d) for d in DEFECTS})


# ------------------------------------------------------------------- extract
def long_runs(m, L):
    """Mark pixels that sit inside a horizontal run of at least L dark pixels."""
    import numpy as np
    c = np.zeros((m.shape[0], m.shape[1] + 1), np.int32); c[:, 1:] = np.cumsum(m, axis=1)
    full = (c[:, L:] - c[:, :-L]) == L
    c2 = np.zeros((m.shape[0], full.shape[1] + 1), np.int32); c2[:, 1:] = np.cumsum(full, axis=1)
    x = np.arange(m.shape[1])
    return (c2[:, np.minimum(x + 1, full.shape[1])] - c2[:, np.maximum(x - L + 1, 0)]) > 0


def cleanup(path, dpi, out):
    """Optional pre-processing: upscale to 200 dpi, straighten (projection profile, -4 to 4 degrees), blank ruled lines."""
    import numpy as np
    from PIL import Image
    img = Image.open(path).convert("L")
    if dpi < 200:
        img = img.resize((round(img.width * 200 / dpi), round(img.height * 200 / dpi)), Image.LANCZOS)
    ink = Image.fromarray(255 - np.asarray(img.resize((img.width // 4, img.height // 4))))
    best = max(np.arange(-4, 4.01, 0.5), key=lambda g: np.var(np.asarray(ink.rotate(g, fillcolor=0)).sum(axis=1)))
    img = img.rotate(best, resample=Image.BICUBIC, fillcolor=255)
    g = np.asarray(img)
    dark, L = g < 200, 25
    thin_h = ~np.roll(dark, 3, axis=0) & ~np.roll(dark, -3, axis=0)  # a ruled line is thin
    thin_v = ~np.roll(dark, 3, axis=1) & ~np.roll(dark, -3, axis=1)
    h = g.copy(); h[(long_runs(dark, L) & thin_h) | (long_runs(dark.T, L).T & thin_v)] = 255
    Image.fromarray(h).save(out, dpi=(200, 200))
    return out, 200


def read_words(truth, folder, prep="none"):
    """Words with page, box in points, text and confidence. Digital PDFs use the text layer, scans use Tesseract."""
    import pymupdf
    from PIL import Image
    words = []
    if truth["tier"] == "digital":
        for p, pg in enumerate(pymupdf.open(str(folder / f"{truth['id']}.pdf"))):
            for x0, y0, x1, y1, t, *_ in pg.get_text("words"):
                words.append({"p": p, "x0": x0, "y0": y0, "x1": x1, "y1": y1, "t": t, "c": 100, "ln": None})
        return words
    for p in range(truth["pages"]):
        path = next(folder.glob(f"{truth['id']}_p{p + 1}.*"))
        dpi = Image.open(path).info.get("dpi", (200, 200))[0]
        s = 72 / dpi
        if prep == "cleanup":
            path, dpi = cleanup(path, dpi, folder / "_tmp_clean.png")
            s = 72 / dpi
        env = dict(os.environ, OMP_THREAD_LIMIT="1")
        tsv = subprocess.run(["tesseract", str(path), "stdout", "--psm", "6", "tsv"], capture_output=True, text=True, env=env).stdout
        for row in tsv.split("\n")[1:]:
            f = row.split("\t")
            if len(f) == 12 and f[0] == "5" and f[11].strip():
                l, tp, w, h = int(f[6]), int(f[7]), int(f[8]), int(f[9])
                words.append({"p": p, "x0": l * s, "y0": tp * s, "x1": (l + w) * s, "y1": (tp + h) * s, "t": f[11].strip(),
                              "c": float(f[10]), "ln": (p, f[2], f[3], f[4])})
    return words


def make_lines(words):
    by, free = {}, []
    for w in words:
        (by.setdefault(w["ln"], []) if w["ln"] else free).append(w)
    groups = list(by.values())
    for p in sorted({w["p"] for w in free}):
        cur = []
        for w in sorted([w for w in free if w["p"] == p], key=lambda w: (w["y0"] + w["y1"]) / 2):
            yc = (w["y0"] + w["y1"]) / 2
            if cur and abs(yc - sum((x["y0"] + x["y1"]) / 2 for x in cur) / len(cur)) > 0.5 * (w["y1"] - w["y0"]):
                groups.append(cur); cur = []
            cur.append(w)
        if cur: groups.append(cur)
    out = []
    for g in groups:
        g = sorted(g, key=lambda w: w["x0"])
        out.append({"p": g[0]["p"], "y": sum((w["y0"] + w["y1"]) / 2 for w in g) / len(g), "words": g, "text": " ".join(w["t"] for w in g)})
    return sorted(out, key=lambda L: (L["p"], L["y"]))


DIG = str.maketrans("OolIS|", "001115")
MONEY = re.compile(r"(?<![\d.,])\d{1,3}(?:[.,]\d{3})*[.,]\d{2}(?!\d)|(?<![\d.,])\d+[.,]\d{2}(?!\d)")
SUB = re.compile(r"(?i)^\W*(?:sub\s*-?\s*total|net(?:\s+amount)?)\b")
TAX = re.compile(r"(?i)^\W*(?:sales\s+)?(?:tax|vat|gst)(?![a-z])")
TOT = re.compile(r"(?i)^\W*(?:grand\s+)?(?:total(?:\s*(?:due|amount))?|amount\s*(?:payable|due)|balance\s*due)(?![a-z])")
VOC = {"desc": ["description", "item", "details"], "qty": ["qty", "quantity"], "unit": ["unit", "price", "rate"], "amt": ["amount", "total", "line"]}
DATES = [(re.compile(r"\b(\d{4})-(\d{2})-(\d{2})\b"), "ymd"), (re.compile(r"\b(\d{1,2})\s+([A-Z][a-z]{2})\s+(\d{4})\b"), "dmy"),
         (re.compile(r"\b(\d{2})\.(\d{2})\.(\d{4})\b"), "dot"), (re.compile(r"\b([A-Z][a-z]{2})\s+(\d{1,2}),\s*(\d{4})\b"), "mdy")]


def to_money(tok):
    t = tok.translate(DIG) if sum(ch.isdigit() for ch in tok) >= len(tok) // 2 else tok
    m = re.fullmatch(r"([\d.,]*\d)[.,](\d{2})", t)
    return Decimal(re.sub(r"[.,]", "", m.group(1)) + "." + m.group(2)) if m else None


def to_date(s):
    for rx, kind in DATES:
        m = rx.search(s)
        if not m: continue
        g = m.groups()
        try:
            if kind == "ymd": return str(datetime.date(int(g[0]), int(g[1]), int(g[2])))
            if kind == "dmy": return str(datetime.date(int(g[2]), MON.index(g[1]) + 1, int(g[0])))
            if kind == "dot": return str(datetime.date(int(g[2]), int(g[1]), int(g[0])))
            return str(datetime.date(int(g[2]), MON.index(g[0]) + 1, int(g[1])))
        except ValueError:
            continue
    return None


def conf_of(L, s):
    return min([w["c"] for w in L["words"] if w["t"] in s] or [100])


def header_cells(L):
    cells = []
    for w in L["words"]:
        m = {k: difflib.get_close_matches(w["t"].lower().strip(":"), v, 1, 0.75) for k, v in VOC.items()}
        k = next((k for k, v in m.items() if v), None)
        if k and cells and cells[-1]["k"] == k and w["x0"] - cells[-1]["x1"] < 15: cells[-1]["x1"] = w["x1"]
        elif k: cells.append({"k": k, "x0": w["x0"], "x1": w["x1"]})
    return cells if {c["k"] for c in cells} == set(VOC) else None


def extract(words):
    words = [dict(w, t=w["t"].strip("|;_[]")) for w in words]  # stray rule fragments become empty tokens
    lines = make_lines([w for w in words if re.search(r"\w", w["t"])])
    e = {k: None for k in HEADER}; e.update(rate=None, lines=[]); conf = []
    for L in lines:
        m = re.search(r"\b(USD|EUR|GBP)\b", L["text"])
        if m: e["currency"] = m.group(1); break
    for L in lines:  # vendor: leading words of the first top line, cut at the first wide gap
        if L["p"]: break
        ws, cut = L["words"], len(L["words"])
        for i in range(1, len(ws)):
            if ws[i]["x0"] - ws[i - 1]["x1"] > 25: cut = i; break
        name = " ".join(w["t"] for w in ws[:cut])
        if re.search(r"[A-Za-z]{3}", name) and not re.match(r"(?i)\W*(tax\s+)?invoice\b", name): e["vendor"] = name; break
    for strict in (True, False):  # invoice number: prefer a line that says invoice
        for L in lines:
            if L["p"]: break
            m = re.search(r"\b((?!PO)[A-Z][A-Zl1I!|]{1,2})\s?-\s?([0-9OolIS]{5})\b", L["text"])
            if m and (not strict or re.search(r"(?i)\binv", L["text"])):
                e["invoice_number"] = f"{m.group(1).translate(str.maketrans('l1!|', 'IIII'))}-{m.group(2).translate(DIG)}"; conf.append(conf_of(L, m.group(0))); break
        if e["invoice_number"]: break
    for L in lines:
        m = re.search(r"\bP[O0]\s?[-\u2013]?\s?([0-9OolIS]{5})\b", L["text"])
        if m: e["po"] = "PO-" + m.group(1).translate(DIG); conf.append(conf_of(L, m.group(0))); break
    for L in lines:
        if L["p"] == 0 and "due" not in L["text"].lower() and to_date(L["text"]):
            e["date"] = to_date(L["text"]); conf.append(conf_of(L, L["text"])); break
    hi = next((i for i, L in enumerate(lines) if header_cells(L)), None)
    stop = len(lines)
    for i, L in enumerate(lines):  # totals: anchored labels below the table header
        if hi is not None and i <= hi: continue
        nums = [(w, to_money(w["t"])) for w in L["words"] if to_money(w["t"]) is not None]
        if not nums: continue
        key = "subtotal" if SUB.match(L["text"]) else "tax" if TAX.match(L["text"]) else "total" if TOT.match(L["text"]) else None
        if key:
            stop = min(stop, i)
            if key == "total" or e[key] is None:
                e[key] = str(nums[-1][1]); conf.append(nums[-1][0]["c"])
            r = re.search(r"(\d{1,2})\s*%", L["text"])
            if key == "tax" and r: e["rate"] = int(r.group(1))
    if hi is not None:
        cells = header_cells(lines[hi])
        d = next(c for c in cells if c["k"] == "desc")
        right = [c["x0"] for c in cells if c["k"] != "desc" and c["x0"] > d["x0"]]
        lo, hi_x = d["x0"] - 14, (min(right) - 14 if right else 9999)
        num = [c for c in cells if c["k"] != "desc"]
        for L in lines[hi + 1:stop]:
            row = {"desc": [], "qty": [], "unit": [], "amt": []}
            for w in L["words"]:
                if lo <= w["x0"] < hi_x: row["desc"].append(w["t"])
                else:
                    xc = (w["x0"] + w["x1"]) / 2
                    row[min(num, key=lambda c: abs((c["x0"] + c["x1"]) / 2 - xc))["k"]].append(w["t"])
            qty = "".join(row["qty"]).translate(DIG)
            r = {"desc": " ".join(row["desc"]), "qty": int(qty) if qty.isdigit() else None,
                 "unit": to_money("".join(row["unit"])), "amount": to_money("".join(row["amt"]))}
            if any(r[k] is not None for k in ("qty", "unit", "amount")):
                e["lines"].append({k: (str(v) if isinstance(v, Decimal) else v) for k, v in r.items()})
    e["conf"] = min(conf) if conf else 0
    return e


def vendor_adapter(folder, truth):
    """Return the same dict as extract(): header fields, rate, lines and conf. Call your vendor here."""
    raise NotImplementedError("plug a vendor in; scoring is unchanged")


def run(a):
    folder = Path(a.dir); res = {}
    for iid in json.loads((folder / "manifest.json").read_text()):
        t = json.loads((folder / f"{iid}.json").read_text())
        t0 = time.perf_counter()
        e = vendor_adapter(folder, t) if a.engine == "vendor" else extract(read_words(t, folder, a.prep))
        e["seconds"], e["pages"] = time.perf_counter() - t0, t["pages"]
        res[iid] = e
    (folder / f"extractions{a.tag}.json").write_text(json.dumps(res, indent=1))
    print("extracted", len(res), "invoices,", round(sum(e["seconds"] for e in res.values()), 1), "s")


# --------------------------------------------------------------------- score
def norm(s): return re.sub(r"[^a-z0-9]", "", (s or "").lower())
def D(x): return None if x is None else Decimal(str(x))


def field_ok(k, truth, e):
    a, b = truth.get(k), e.get(k)
    if k in ("subtotal", "tax", "total"): return b is not None and D(a) == D(b)
    if k == "po": return norm(a) == norm(b)
    if k in ("vendor", "invoice_number"): return bool(b) and norm(a) == norm(b)
    return a == b


def match_rows(truth, e, desc=True):
    used, hit = set(), 0
    for g in truth["lines"]:
        for j, r in enumerate(e["lines"]):
            if j in used: continue
            if (r["qty"] == g["qty"] and D(r["unit"]) == D(g["unit"]) and D(r["amount"]) == D(g["amount"])
                    and (not desc or norm(r["desc"]) == norm(g["desc"]))):
                used.add(j); hit += 1; break
    return hit


def rules(ordered):
    """The exception rules. A flagged invoice goes to a person; an unflagged one is released untouched."""
    seen, out = {}, {}
    for iid, e in ordered:
        fl = []
        miss = [k for k in ("vendor", "invoice_number", "date", "total") if not e.get(k)]
        if miss: fl.append("missing:" + "+".join(miss))
        if not e.get("po"): fl.append("missing:po")
        sub, tax, tot = D(e.get("subtotal")), D(e.get("tax")), D(e.get("total"))
        amts = [D(l["amount"]) for l in e["lines"]]
        if sub is None or None in amts or abs(sum(amts, Decimal(0)) - sub) > TOL: fl.append("reconcile:lines")
        if None in (sub, tax, tot) or abs(sub + tax - tot) > TOL: fl.append("reconcile:total")
        if any(l["qty"] is None or l["unit"] is None or l["amount"] is None or abs(l["qty"] * D(l["unit"]) - D(l["amount"])) > TOL for l in e["lines"]):
            fl.append("reconcile:line_math")
        if e.get("rate") is not None and None not in (sub, tax) and abs(q2(sub * e["rate"] / 100) - tax) > TOL: fl.append("tax_rate")
        key = (norm(e.get("vendor")), norm(e.get("invoice_number")))
        if all(key):
            if key in seen: fl.append("duplicate")
            else: seen[key] = iid
        if e.get("conf", 0) < CONF_MIN: fl.append("low_conf")
        out[iid] = fl
    return out


REASON = {"wrong_total": "reconcile:total", "tax_mismatch": "tax_rate", "missing_po": "missing:po", "duplicate": "duplicate"}


def wilson(k, n, z=1.96):
    if n == 0: return (0.0, 0.0)
    p = k / n; d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d; h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return (max(0.0, c - h), min(1.0, c + h))


def boot(rows, num, den, reps=2000, seed=7):
    """95 percent interval for sum(num)/sum(den), resampling invoices."""
    r = random.Random(seed); n = len(rows); vals = []
    for _ in range(reps):
        s = [rows[r.randrange(n)] for _ in range(n)]
        d = sum(x[den] for x in s)
        if d: vals.append(sum(x[num] for x in s) / d)
    vals.sort()
    return (vals[int(0.025 * len(vals))], vals[int(0.975 * len(vals)) - 1]) if vals else (0, 0)


def cost(pages, flagged, leaked, clean):
    """Hypothetical cost per clean invoice. Inputs are assumptions, not prices; change them."""
    people = (flagged * REVIEW_MIN + leaked * REWORK_MIN) / 60 * RATE_PER_HOUR
    return float((PAGE_PRICE * pages + Decimal(str(people))) / clean) if clean else None


def score(a):
    folder = Path(a.dir)
    order = json.loads((folder / "manifest.json").read_text())
    global CONF_MIN
    CONF_MIN = a.conf
    ext = json.loads((folder / f"extractions{a.tag}.json").read_text())
    flags = rules([(i, ext[i]) for i in order])
    rows = []
    for iid in order:
        t, e = json.loads((folder / f"{iid}.json").read_text()), ext[iid]
        ok = {k: field_ok(k, t, e) for k in HEADER}
        full, nod, n_gt, n_ex = match_rows(t, e), match_rows(t, e, False), len(t["lines"]), len(e["lines"])
        doc = all(ok.values()) and full == n_gt == n_ex
        amts = [D(l["amount"]) for l in e["lines"]]
        sub, tax, tot = D(e.get("subtotal")), D(e.get("tax")), D(e.get("total"))
        rec = (sub is not None and None not in amts and abs(sum(amts, Decimal(0)) - sub) <= TOL and None not in (tax, tot) and abs(sub + tax - tot) <= TOL)
        fl, clean = flags[iid], t["defect"] == "none"
        rows.append({"id": iid, "template": t["template"], "tier": t["tier"], "defect": t["defect"], "pages": t["pages"],
                     "hdr_ok": sum(ok.values()), "hdr_n": len(HEADER), "rows_gt": n_gt, "rows_ext": n_ex, "rows_ok": full, "rows_ok_nodesc": nod,
                     "doc_ok": int(doc), "reconcile": int(rec), "flags": "|".join(fl), "flagged": int(bool(fl)), "clean": int(clean),
                     "stp": int(clean and not fl and doc), "leaked": int(not fl and not doc), "justified": int(bool(fl) and not doc),
                     "needless": int(bool(fl) and doc), "caught": int(not clean and bool(fl)),
                     "right_reason": int(not clean and REASON[t["defect"]] in fl), "seconds": round(e["seconds"], 3),
                     **{f"ok_{k}": int(v) for k, v in ok.items()}})
    with open(folder / f"results{a.tag}.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)

    def block(rs):
        cl = [r for r in rs if r["clean"]]; sd = [r for r in rs if not r["clean"]]
        pr = lambda k, n: {"k": k, "n": n, "p": k / n if n else None, "ci": wilson(k, n)}
        o = {"n": len(rs), "n_clean": len(cl), "n_seeded": len(sd)}
        o["header"] = {"p": sum(r["hdr_ok"] for r in rs) / sum(r["hdr_n"] for r in rs), "ci": boot(rs, "hdr_ok", "hdr_n")}
        o["lines"] = {"p": sum(r["rows_ok"] for r in rs) / sum(r["rows_gt"] for r in rs), "ci": boot(rs, "rows_ok", "rows_gt"),
                      "precision": sum(r["rows_ok"] for r in rs) / max(1, sum(r["rows_ext"] for r in rs)),
                      "nodesc": sum(r["rows_ok_nodesc"] for r in rs) / sum(r["rows_gt"] for r in rs)}
        o["doc"] = pr(sum(r["doc_ok"] for r in rs), len(rs))
        o["reconcile"] = pr(sum(r["reconcile"] for r in cl), len(cl))
        o["stp"] = pr(sum(r["stp"] for r in cl), len(cl))
        o["clean_flow"] = {k: sum(r[k] for r in cl) for k in ("stp", "needless", "justified", "leaked")}
        o["false_stop"] = pr(sum(r["flagged"] for r in cl), len(cl))
        o["catch"] = pr(sum(r["caught"] for r in sd), len(sd))
        o["right_reason"] = pr(sum(r["right_reason"] for r in sd), len(sd))
        o["catch_by_type"] = {d: pr(sum(r["caught"] for r in sd if r["defect"] == d), sum(1 for r in sd if r["defect"] == d)) for d in DEFECTS}
        o["sec_per_page"] = sum(r["seconds"] for r in rs) / sum(r["pages"] for r in rs)
        o["sec_per_invoice"] = sum(r["seconds"] for r in rs) / len(rs)
        o["cost_per_clean"] = cost(sum(r["pages"] for r in cl), sum(r["flagged"] for r in cl), sum(r["leaked"] for r in cl), len(cl))
        # independence model: each header field and each row is one unit that is right with probability p
        units = sum(r["hdr_n"] + r["rows_gt"] for r in rs); right = sum(r["hdr_ok"] + r["rows_ok"] for r in rs); p = right / units
        o["indep"] = {"unit_acc": p, "mean_units": units / len(rs), "predicted_doc": sum(p ** (r["hdr_n"] + r["rows_gt"]) for r in rs) / len(rs)}
        return o
    res = {"overall": block(rows), "by_tier": {t: block([r for r in rows if r["tier"] == t]) for t in TIERS},
           "by_template": {t: block([r for r in rows if r["template"] == t]) for t in TEMPLATES},
           "doc_grid": {f"{tp}/{ti}": [sum(r["doc_ok"] for r in rows if r["template"] == tp and r["tier"] == ti), sum(1 for r in rows if r["template"] == tp and r["tier"] == ti)]
                        for tp in TEMPLATES for ti in TIERS},
           "field_acc": {k: sum(r[f"ok_{k}"] for r in rows) / len(rows) for k in HEADER},
           "field_acc_by_tier": {t: {k: sum(r[f"ok_{k}"] for r in rows if r["tier"] == t) / sum(1 for r in rows if r["tier"] == t) for k in HEADER} for t in TIERS},
           "flag_counts": {}, "assumptions": {"review_min": REVIEW_MIN, "rework_min": REWORK_MIN, "rate_per_hour": RATE_PER_HOUR, "page_price": str(PAGE_PRICE), "conf_min": CONF_MIN}}
    for r in rows:
        for f in filter(None, r["flags"].split("|")):
            f = "missing:" + f[8:].split("+")[0] if f.startswith("missing:") and f != "missing:po" else f
            res["flag_counts"][f] = res["flag_counts"].get(f, 0) + 1
    (folder / f"results{a.tag}.json").write_text(json.dumps(res, indent=1))
    o = res["overall"]
    print(f"invoices {o['n']} (clean {o['n_clean']}, seeded {o['n_seeded']}); header {o['header']['p']:.3f}; lines {o['lines']['p']:.3f}; doc {o['doc']['p']:.3f}; "
          f"reconcile {o['reconcile']['p']:.3f}; STP {o['stp']['p']:.3f}; catch {o['catch']['p']:.3f}; false stop {o['false_stop']['p']:.3f}")


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
    g = sp.add_parser("generate"); g.add_argument("dir"); g.add_argument("--seed", type=int, default=2026); g.add_argument("--per-cell", type=int, default=19)
    r = sp.add_parser("run"); r.add_argument("dir"); r.add_argument("--engine", choices=["baseline", "vendor"], default="baseline"); r.add_argument("--prep", choices=["none", "cleanup"], default="none"); r.add_argument("--tag", default="")
    s = sp.add_parser("score"); s.add_argument("dir"); s.add_argument("--tag", default=""); s.add_argument("--conf", type=float, default=CONF_MIN)
    a = ap.parse_args()
    {"generate": generate, "run": run, "score": score}[a.cmd](a)
