#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# LOCKED CALCULATION AREA — Read docs/LOCKED_STATEMENT_COMMISSION_RULES.md before
# editing. Do not modify statement/payroll/commission calculation logic without explicit
# developer approval.
#
# Locked 2026-08-30. This file is on the Protected Files list.
#   Architecture and restore procedure: docs/recovery/STATEMENT_PARSER_ARCHITECTURE.md
#   Governing rules:                    docs/recovery/STATEMENT_READING_PROTOCOL.md
#
# Three invariants that must survive any edit:
#   R1  The printed Total Paid is the answer. Read it; never recompute or adjust it.
#   R9  Line items must sum to the printed Total Paid to the cent. On failure: WARN,
#       never block and never silently accept.
#   §7  Repair a non-footing line ONLY against evidence - another statement reprinting
#       the same policy for the same agent with cents - and only when the fix is unique
#       and closes R9 exactly. If you cannot evidence it, refuse and warn.
#
# Rollback: set ENABLE_GEOMETRIC_EXTRACTOR = false in settings/parser.conf. One line, no
# deploy; the whole engine goes inert. Never hard-delete this file.
#
# After ANY edit: python3 -m py_compile on this file, then
# `cd /home/litcrm/parser_rebuild && python3 classifier_tests.py` (must print ALL
# CLASSIFIER TESTS PASS), then re-run the six reference statements in §14.4 of the
# architecture doc. STMT-000182 MUST still fail R9 by 0.10 - that refusal is a feature.
#
"""
stmt_geom_extract.py  --  Geometric, multi-strategy commission-statement extractor.

Rebuild of the LIT-CRM statement EXTRACTION step only. Emits the exact line shape the
existing pipeline consumes:
    policy_number, agent_name, insured_name, carrier, split, comp_rate,
    commission_amount, paid_date, notes
plus provenance/confidence metadata under `_prov`.

Design rules (see docs/recovery/STATEMENT_READING_PROTOCOL.md):
  * Columns are derived from measured word x-positions (gutter detection), never from
    header-label offsets.  (defeats failure mode 6, 10)
  * Rows are built from a geometric SPINE (the commission column) and every other
    column is attached by optimal monotonic y-alignment, so the ~4.6pt cell jitter
    cannot move an amount onto a neighbouring row.  (defeats failure mode 7)
  * A token is money only if it sits in the commission band. Percent / split /
    policy / date tokens can never become money.  (defeats failure mode 2)
  * Footer `Total Paid` is captured as the statement total, excluded from the body
    both by position and by value.  (defeats failure mode 1)
  * Amount regex accepts optional decimals, 1 decimal, no $ sign, parentheses,
    leading and trailing minus.  (defeats failure modes 3, 4, 5)
  * Bands are pooled across pages, so a page-2 with no header inherits them.
    (defeats failure mode 9)
  * Two fully independent word sources (pdfplumber, poppler pdftotext -bbox-layout)
    run the same geometry and are cross-validated; OCR is a last resort.

Usage:
    stmt_geom_extract.py <pdf> [--json] [--debug]
    stmt_geom_extract.py --batch <listfile>     # one pdf path per line -> JSONL
"""

import sys, os, re, json, math, subprocess, tempfile, hashlib
from collections import defaultdict

VERSION = "geom-1.0.0"

# ---------------------------------------------------------------- token classifiers

# Money: optional (), optional leading/trailing '-', optional '$', thousands commas,
# 0/1/2 decimal places.  Deliberately permissive; the COLUMN is what makes it money.
_MONEY_CORE = r'\$?\s?-?\d{1,3}(?:,\d{3})*(?:\.\d{1,2})?|\$?\s?-?\d+(?:\.\d{1,2})?'
MONEY_RE = re.compile(r'^\(?\s*-?\s*(?:' + _MONEY_CORE + r')\s*\)?-?$')
# Percent (accept comma decimal typo e.g. "57,5%")
PCT_RE = re.compile(r'^-?\d{1,3}(?:[.,]\d{1,3})?\s*%$')
# Split: bare integer 0..100, or n/n, or n% when short
SPLIT_RE = re.compile(r'^\d{1,3}(?:\s*/\s*\d{1,3})?%?$')
# Policy number: has a digit, no spaces, mostly alnum/dash, len>=5
POLICY_RE = re.compile(r'^(?=.*\d)[A-Za-z0-9][A-Za-z0-9\-/_.]{3,}$')
DATE_RE = re.compile(r'^\d{1,2}/\d{1,2}/\d{2,4}$')

HEADER_TOKENS = {'agent', 'name', 'company', 'policy', '#', 'insured', 'split',
                 'comp', 'rate', 'commission', 'premium', 'product', 'writing',
                 'effective', 'date', 'type', 'amount', 'paid'}
HEADER_STRONG = ['commission', 'policy', 'insured', 'split', 'company', 'rate']

FOOTER_LABELS = ['total paid', 'total due', 'grand total', 'net total', 'total:',
                 'total commission', 'amount paid']

TITLE_HINTS = ['detailed compensation statement', 'compensation statement',
               'commission statement', 'date:', 'statement date', 'page ']


def parse_money(tok):
    """Return float or None. Handles $405, -68.4, ($815.51), 552.74, -$587.27, 1,089.79."""
    if tok is None:
        return None
    s = str(tok).strip()
    if s == '':
        return None
    neg = False
    if s.startswith('(') and s.endswith(')'):
        neg = True
        s = s[1:-1].strip()
    if s.endswith('-'):          # trailing minus (rare accounting form)
        neg = True
        s = s[:-1].strip()
    if s.startswith('-'):
        neg = True
        s = s[1:].strip()
    s = s.replace('$', '').replace(' ', '')
    if s.startswith('-'):
        neg = True
        s = s[1:]
    s = s.replace(',', '')
    if s == '' or not re.match(r'^\d+(\.\d{1,4})?$', s):
        return None
    v = float(s)
    return -v if neg else v


def looks_money(tok):
    t = str(tok).strip()
    if t == '':
        return False
    if PCT_RE.match(t):
        return False
    if DATE_RE.match(t):
        return False
    if not MONEY_RE.match(t):
        return False
    return parse_money(t) is not None


def looks_pct(tok):
    return bool(PCT_RE.match(str(tok).strip()))


def looks_split(tok):
    t = str(tok).strip()
    if not SPLIT_RE.match(t):
        return False
    if t.endswith('%'):
        return True
    try:
        return 0 <= int(t.split('/')[0]) <= 100
    except Exception:
        return False


def looks_policy(tok):
    t = str(tok).strip()
    if DATE_RE.match(t):
        return False
    if looks_money(t) and ('$' in t or '.' in t):
        return False
    return bool(POLICY_RE.match(t)) and len(t) >= 5


def looks_name(tok):
    t = str(tok).strip()
    if t == '':
        return False
    return bool(re.match(r"^[A-Za-zÀ-ÿ'\.\-]{2,}$", t))


# ---------------------------------------------------------------- word sources

class Word(object):
    __slots__ = ('x0', 'x1', 'top', 'bottom', 'text', 'page')

    def __init__(self, x0, x1, top, bottom, text, page):
        self.x0 = float(x0); self.x1 = float(x1)
        self.top = float(top); self.bottom = float(bottom)
        self.text = text; self.page = page

    @property
    def yc(self):
        return (self.top + self.bottom) / 2.0

    @property
    def xc(self):
        return (self.x0 + self.x1) / 2.0

    def __repr__(self):
        return "W(%s p%d x%.1f-%.1f y%.1f)" % (self.text, self.page, self.x0, self.x1, self.yc)


def words_pdfplumber(path):
    import pdfplumber
    out = []
    dims = []
    with pdfplumber.open(path) as pdf:
        for pi, page in enumerate(pdf.pages):
            dims.append((float(page.width), float(page.height)))
            try:
                ws = page.extract_words(use_text_flow=False, keep_blank_chars=False)
            except Exception:
                ws = []
            for w in ws:
                t = (w.get('text') or '').strip()
                if t == '':
                    continue
                out.append(Word(w['x0'], w['x1'], w['top'], w['bottom'], t, pi))
    return out, dims


_BBOX_WORD_RE = re.compile(
    r'<word xMin="([\d.\-]+)" yMin="([\d.\-]+)" xMax="([\d.\-]+)" yMax="([\d.\-]+)">(.*?)</word>',
    re.S)
_BBOX_PAGE_RE = re.compile(r'<page width="([\d.\-]+)" height="([\d.\-]+)">')


def _unxml(s):
    return (s.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>')
             .replace('&quot;', '"').replace('&apos;', "'"))


def words_poppler_bbox(path):
    try:
        xml = subprocess.check_output(['pdftotext', '-bbox-layout', path, '-'],
                                      stderr=subprocess.DEVNULL).decode('utf-8', 'replace')
    except Exception:
        return [], []
    out = []
    dims = []
    # split by page
    parts = re.split(r'(<page width="[\d.\-]+" height="[\d.\-]+">)', xml)
    pi = -1
    for chunk in parts:
        m = _BBOX_PAGE_RE.match(chunk or '')
        if m:
            pi += 1
            dims.append((float(m.group(1)), float(m.group(2))))
            continue
        if pi < 0:
            continue
        for wm in _BBOX_WORD_RE.finditer(chunk or ''):
            t = _unxml(wm.group(5)).strip()
            if t == '':
                continue
            out.append(Word(float(wm.group(1)), float(wm.group(3)),
                            float(wm.group(2)), float(wm.group(4)), t, pi))
    return out, dims


def words_ocr(path, max_pages=12):
    """Last-resort OCR word boxes via tesseract TSV on rendered pages."""
    out = []
    dims = []
    tmpd = tempfile.mkdtemp(prefix='stmtocr_', dir=os.environ.get('STMT_TMP', '/home/litcrm/tmp'))
    try:
        subprocess.check_call(['pdftoppm', '-r', '200', '-png', '-f', '1',
                               '-l', str(max_pages), path, os.path.join(tmpd, 'pg')],
                              stderr=subprocess.DEVNULL)
        pngs = sorted(f for f in os.listdir(tmpd) if f.endswith('.png'))
        for pi, fn in enumerate(pngs):
            fp = os.path.join(tmpd, fn)
            try:
                tsv = subprocess.check_output(['tesseract', fp, 'stdout', '--psm', '6', 'tsv'],
                                              stderr=subprocess.DEVNULL).decode('utf-8', 'replace')
            except Exception:
                continue
            scale = 72.0 / 200.0
            maxx = maxy = 0.0
            for ln in tsv.splitlines()[1:]:
                f = ln.split('\t')
                if len(f) < 12:
                    continue
                try:
                    conf = float(f[10])
                except Exception:
                    continue
                t = f[11].strip()
                if t == '' or conf < 30:
                    continue
                left, top, wdt, hgt = (float(f[6]), float(f[7]), float(f[8]), float(f[9]))
                x0 = left * scale; y0 = top * scale
                x1 = (left + wdt) * scale; y1 = (top + hgt) * scale
                maxx = max(maxx, x1); maxy = max(maxy, y1)
                out.append(Word(x0, x1, y0, y1, t, pi))
            dims.append((maxx, maxy))
    except Exception:
        pass
    finally:
        try:
            import shutil
            shutil.rmtree(tmpd, ignore_errors=True)
        except Exception:
            pass
    return out, dims


# ---------------------------------------------------------------- geometry

def cluster_strips(words, tol=3.0):
    """Coarse y-clustering of a page's words into visual strips."""
    ws = sorted(words, key=lambda w: (w.yc, w.x0))
    strips = []
    cur = []
    for w in ws:
        if not cur:
            cur = [w]
            continue
        if abs(w.yc - (sum(x.yc for x in cur) / len(cur))) <= tol:
            cur.append(w)
        else:
            strips.append(sorted(cur, key=lambda z: z.x0))
            cur = [w]
    if cur:
        strips.append(sorted(cur, key=lambda z: z.x0))
    return strips


def strip_text(strip):
    return ' '.join(w.text for w in strip)


def classify_strip(strip):
    txt = strip_text(strip).lower()
    toks = [w.text.lower().strip(':#') for w in strip]
    hits = sum(1 for h in HEADER_STRONG if h in toks)
    if hits >= 3:
        return 'HEADER'
    for lab in FOOTER_LABELS:
        if lab in txt:
            return 'FOOTER'
    for h in TITLE_HINTS:
        if h in txt:
            return 'TITLE'
    if re.match(r'^page\s+\d+', txt):
        return 'TITLE'
    return 'BODY'


def detect_bands(words, gutter_min=6.0):
    """Merge word x-intervals; a gap >= gutter_min opens a new column band."""
    iv = sorted(((w.x0, w.x1) for w in words))
    if not iv:
        return []
    bands = []
    cx0, cx1 = iv[0]
    for a, b in iv[1:]:
        if a - cx1 >= gutter_min:
            bands.append([cx0, cx1])
            cx0, cx1 = a, b
        else:
            cx1 = max(cx1, b)
    bands.append([cx0, cx1])
    return bands


def band_of(w, bands):
    """Index of the band containing the word (max overlap)."""
    best, bestov = -1, 0.0
    for i, (a, b) in enumerate(bands):
        ov = min(w.x1, b) - max(w.x0, a)
        if ov > bestov:
            bestov, best = ov, i
    if best >= 0:
        return best
    # fall back to nearest band by centre
    dists = [min(abs(w.xc - a), abs(w.xc - b)) for a, b in bands]
    return int(min(range(len(bands)), key=lambda i: dists[i])) if bands else -1


def cells_in_band(words, tol=2.6):
    """Group a band's words into cells by tight y-clustering; join left-to-right."""
    ws = sorted(words, key=lambda w: (w.yc, w.x0))
    cells = []
    cur = []
    for w in ws:
        if not cur:
            cur = [w]
            continue
        ref = sum(x.yc for x in cur) / len(cur)
        if abs(w.yc - ref) <= tol:
            cur.append(w)
        else:
            cells.append(cur)
            cur = [w]
    if cur:
        cells.append(cur)
    out = []
    for c in cells:
        c = sorted(c, key=lambda z: z.x0)
        out.append({
            'y': sum(w.yc for w in c) / len(c),
            'x0': min(w.x0 for w in c),
            'x1': max(w.x1 for w in c),
            'text': ' '.join(w.text for w in c),
            'tokens': [w.text for w in c],
            'words': c,
        })
    out.sort(key=lambda c: c['y'])
    return out


def monotonic_align(spine_y, cells, max_dy):
    """
    Optimal monotonic injective assignment of `cells` (ordered by y) to spine rows
    (ordered by y), minimising total |dy|.  Returns list len(spine) of cell-or-None
    plus the list of unassigned cell indices.
    DP over (cell_i, row_j).
    """
    n = len(cells); m = len(spine_y)
    if n == 0 or m == 0:
        return [None] * m, list(range(n))
    INF = float('inf')
    # dp[i][j] = min cost using first i cells against first j rows
    dp = [[INF] * (m + 1) for _ in range(n + 1)]
    bk = [[0] * (m + 1) for _ in range(n + 1)]
    dp[0][0] = 0.0
    for j in range(m + 1):
        dp[0][j] = 0.0
        bk[0][j] = 1  # skip row
    SKIP_CELL = 1000.0        # penalty for leaving a cell unplaced
    for i in range(1, n + 1):
        for j in range(0, m + 1):
            best = INF; b = 0
            # 2: skip this cell (unplaced)
            if dp[i - 1][j] + SKIP_CELL < best:
                best = dp[i - 1][j] + SKIP_CELL; b = 2
            if j > 0:
                # 1: leave row j-1 empty
                if dp[i][j - 1] < best:
                    best = dp[i][j - 1]; b = 1
                # 3: place cell i-1 into row j-1
                d = abs(cells[i - 1]['y'] - spine_y[j - 1])
                if d <= max_dy and dp[i - 1][j - 1] + d < best:
                    best = dp[i - 1][j - 1] + d; b = 3
            dp[i][j] = best; bk[i][j] = b
    out = [None] * m
    unplaced = []
    i, j = n, m
    while i > 0 or j > 0:
        b = bk[i][j]
        if i == 0:
            j -= 1; continue
        if b == 1:
            j -= 1
        elif b == 2:
            unplaced.append(i - 1); i -= 1
        elif b == 3:
            out[j - 1] = cells[i - 1]; i -= 1; j -= 1
        else:
            break
    unplaced.reverse()
    return out, unplaced


# ---------------------------------------------------------------- column labelling

def score_band(cells):
    """Content fingerprint of a band."""
    n = len(cells) or 1
    money = pct = split = policy = name = date = bare = 0
    for c in cells:
        t = c['text'].strip()
        toks = c['tokens']
        if len(toks) == 1:
            if looks_money(t):
                money += 1
            if looks_pct(t):
                pct += 1
            if looks_split(t):
                split += 1
            if looks_policy(t):
                policy += 1
            if DATE_RE.match(t):
                date += 1
            # bare split: integer or n/n, no currency, no decimal point, <= 100
            if re.match(r'^\d{1,3}(?:\s*/\s*\d{1,3})?$', t):
                try:
                    if all(0 <= int(p.strip()) <= 100 for p in t.split('/')):
                        bare += 1
                except Exception:
                    pass
        if all(looks_name(x) for x in toks) and len(toks) >= 1:
            name += 1
    return {'n': len(cells), 'money': money / n, 'pct': pct / n, 'split': split / n,
            'policy': policy / n, 'name': name / n, 'date': date / n,
            'bare_split': bare / n}


def label_bands(bands, band_cells, header_strip):
    """
    Assign semantic labels using CONTENT first, header labels only as a tiebreak.
    Returns dict label -> band index.
    """
    nb = len(bands)
    fps = [score_band(band_cells[i]) for i in range(nb)]
    labels = {}
    used = set()

    # commission = rightmost band that is predominantly money
    for i in range(nb - 1, -1, -1):
        if fps[i]['n'] >= 1 and fps[i]['money'] >= 0.75 and fps[i]['pct'] < 0.5:
            labels['commission'] = i; used.add(i); break
    # comp rate = predominantly percent
    for i in range(nb - 1, -1, -1):
        if i in used:
            continue
        if fps[i]['n'] >= 1 and fps[i]['pct'] >= 0.6:
            labels['comp_rate'] = i; used.add(i); break
    # split = bare small integers / n/n (no $, no decimals), left of comp_rate
    for i in range(nb - 1, -1, -1):
        if i in used:
            continue
        if fps[i]['n'] >= 1 and fps[i]['bare_split'] >= 0.6:
            if 'comp_rate' not in labels or i < labels['comp_rate']:
                labels['split'] = i; used.add(i); break
    # policy = predominantly policy-shaped single tokens
    best_pol, best_sc = -1, 0.0
    for i in range(nb):
        if i in used:
            continue
        if fps[i]['n'] >= 1 and fps[i]['policy'] >= 0.6 and fps[i]['policy'] > best_sc:
            best_sc, best_pol = fps[i]['policy'], i
    if best_pol >= 0:
        labels['policy'] = best_pol; used.add(best_pol)
    # remaining name-ish bands, left to right: agent, company, insured
    remaining = [i for i in range(nb) if i not in used and fps[i]['n'] >= 1]
    remaining.sort()
    nameish = [i for i in remaining if fps[i]['name'] >= 0.4 or fps[i]['n'] > 0]
    # company sits between agent and policy; insured sits right of policy
    pol = labels.get('policy', None)
    left = [i for i in nameish if pol is None or i < pol]
    right = [i for i in nameish if pol is not None and i > pol]
    if len(left) >= 2:
        labels['agent'] = left[0]
        labels['company'] = left[1]
    elif len(left) == 1:
        # single left band: company if it matches carrier words, else agent
        txt = ' '.join(c['text'] for c in band_cells[left[0]]).lower()
        if any(k in txt for k in ('mutual', 'omaha', 'national life', 'ethos', 'americo',
                                  'f&g', 'fidelity', 'transamerica', 'foresters', 'aig',
                                  'corebridge', 'gerber', 'sbli', 'prudential', 'nlg')):
            labels['company'] = left[0]
        else:
            labels['agent'] = left[0]
    if right:
        labels['insured'] = right[0]
        if len(right) > 1 and 'comp_rate' not in labels and 'split' not in labels:
            pass

    # header tiebreak: if header exists and disagrees on agent/company/insured, log
    hdr = {}
    if header_strip:
        for w in header_strip:
            t = w.text.lower().strip(':#')
            if t in ('agent', 'name'):
                hdr.setdefault('agent', []).append(w)
            elif t == 'company':
                hdr.setdefault('company', []).append(w)
            elif t == 'policy':
                hdr.setdefault('policy', []).append(w)
            elif t == 'insured':
                hdr.setdefault('insured', []).append(w)
            elif t == 'split':
                hdr.setdefault('split', []).append(w)
            elif t in ('comp', 'rate'):
                hdr.setdefault('comp_rate', []).append(w)
            elif t == 'commission':
                hdr.setdefault('commission', []).append(w)
    return labels, fps, hdr


# ---------------------------------------------------------------- carrier

def load_carriers(carrier_json_path):
    names = []
    try:
        with open(carrier_json_path, 'r') as fh:
            data = json.load(fh)
    except Exception:
        return names
    def walk(o):
        if isinstance(o, dict):
            for k, v in o.items():
                if k in ('name', 'carrier', 'carrier_name', 'label', 'title') and isinstance(v, str):
                    names.append(v)
                else:
                    walk(v)
        elif isinstance(o, list):
            for v in o:
                walk(v)
        elif isinstance(o, str):
            names.append(o)
    walk(data)
    return [n for n in set(names) if isinstance(n, str) and 2 <= len(n) <= 80]


def carrier_norm(s):
    s = re.sub(r'\(.*?\)', ' ', s or '')
    s = s.lower().replace('&', ' and ')
    s = re.sub(r'[^a-z0-9]+', ' ', s)
    return ' '.join(s.split())


def build_carrier_index(names):
    """alias -> canonical.  Includes the bare form of 'X (Y)' names."""
    idx = {}
    for n in names:
        canon = n.strip()
        keys = {carrier_norm(n)}
        m = re.match(r'^\s*(.+?)\s*\((.+?)\)\s*$', n)
        if m:
            keys.add(carrier_norm(m.group(1)))
            keys.add(carrier_norm(m.group(2)))
        for k in keys:
            if k and k not in idx:
                idx[k] = canon
    return idx


def match_carrier(text, idx):
    k = carrier_norm(text)
    if not k:
        return ''
    if k in idx:
        return idx[k]
    # tolerant: typo of one char, or prefix/substring
    for key, canon in idx.items():
        if not key:
            continue
        if k == key or k.replace(' ', '') == key.replace(' ', ''):
            return canon
    # fuzzy: token overlap >= 0.7 and same first token prefix
    kt = k.split()
    best, bs = '', 0.0
    for key, canon in idx.items():
        st = key.split()
        if not st:
            continue
        inter = len(set(kt) & set(st))
        sc = inter / float(max(len(kt), len(st)))
        if sc > bs:
            bs, best = sc, canon
    if bs >= 0.66:
        return best
    # last resort: edit-distance 1 on the compact form
    kc = k.replace(' ', '')
    for key, canon in idx.items():
        sc = key.replace(' ', '')
        if abs(len(sc) - len(kc)) <= 1 and _lev1(kc, sc):
            return canon
    return text.strip()


def _lev1(a, b):
    if a == b:
        return True
    la, lb = len(a), len(b)
    if abs(la - lb) > 1:
        return False
    i = j = 0; diff = 0
    while i < la and j < lb:
        if a[i] == b[j]:
            i += 1; j += 1
        else:
            diff += 1
            if diff > 1:
                return False
            if la > lb:
                i += 1
            elif lb > la:
                j += 1
            else:
                i += 1; j += 1
    if i < la or j < lb:
        diff += 1
    return diff <= 1


# ---------------------------------------------------------------- core extraction

def extract_with_words(words, dims, carrier_idx, statement_date='', default_carrier=''):
    warn = []
    if not words:
        return {'ok': False, 'lines': [], 'footer_total': None, 'warnings': ['NO_WORDS'],
                'pages': 0}

    pages = defaultdict(list)
    for w in words:
        pages[w.page].append(w)
    npages = max(pages.keys()) + 1

    # --- pass 1: strips + furniture classification per page
    page_info = {}
    footer_totals = []
    header_strip_ref = None
    for pi in sorted(pages.keys()):
        strips = cluster_strips(pages[pi], tol=3.0)
        kinds = [classify_strip(s) for s in strips]
        hdr_i = None
        for i, k in enumerate(kinds):
            if k == 'HEADER':
                hdr_i = i
                break
        ftr_idx = [i for i, k in enumerate(kinds) if k == 'FOOTER']
        page_info[pi] = {'strips': strips, 'kinds': kinds, 'hdr': hdr_i, 'ftr': ftr_idx}
        if hdr_i is not None and header_strip_ref is None:
            header_strip_ref = strips[hdr_i]
        for fi in ftr_idx:
            s = strips[fi]
            # take the rightmost money token on the footer strip
            cand = [w for w in s if looks_money(w.text)]
            if cand:
                cand.sort(key=lambda w: w.x1)
                v = parse_money(cand[-1].text)
                if v is not None:
                    footer_totals.append((pi, s[0].yc, v))

    footer_total = footer_totals[-1][2] if footer_totals else None
    if len(set(round(f[2], 2) for f in footer_totals)) > 1:
        warn.append('MULTIPLE_FOOTER_TOTALS:' + ','.join('%.2f' % f[2] for f in footer_totals))

    # --- body words per page (everything not header/title/footer, and below header,
    #     above footer where those exist)
    body_by_page = {}
    for pi, info in page_info.items():
        strips, kinds = info['strips'], info['kinds']
        hdr_i, ftr_idx = info['hdr'], info['ftr']
        lo = -1e9
        if hdr_i is not None:
            lo = max(w.bottom for w in strips[hdr_i])
        hi = 1e9
        if ftr_idx:
            hi = min(min(w.top for w in strips[i]) for i in ftr_idx)
        bw = []
        for i, s in enumerate(strips):
            if kinds[i] != 'BODY':
                continue
            yc = sum(w.yc for w in s) / len(s)
            if yc <= lo or yc >= hi:
                continue
            bw.extend(s)
        body_by_page[pi] = bw

    all_body = [w for pi in sorted(body_by_page) for w in body_by_page[pi]]
    if not all_body:
        return {'ok': False, 'lines': [], 'footer_total': footer_total,
                'warnings': warn + ['NO_BODY_WORDS'], 'pages': npages}

    # --- pooled column bands (page-2 with no header inherits these)
    bands = detect_bands(all_body, gutter_min=6.0)
    if len(bands) < 2:
        bands = detect_bands(all_body, gutter_min=3.0)

    # Fingerprint cells must be clustered PER PAGE — two pages share the same y range,
    # so pooling words before clustering would fuse row 1 of page 1 with row 1 of page 2.
    band_cells_pooled = {i: [] for i in range(len(bands))}
    for pi in sorted(body_by_page):
        pc = defaultdict(list)
        for w in body_by_page[pi]:
            pc[band_of(w, bands)].append(w)
        for i in range(len(bands)):
            band_cells_pooled[i].extend(cells_in_band(pc.get(i, [])))
    labels, fps, hdr = label_bands(bands, band_cells_pooled, header_strip_ref)

    if 'commission' not in labels:
        return {'ok': False, 'lines': [], 'footer_total': footer_total,
                'warnings': warn + ['NO_COMMISSION_BAND'], 'pages': npages,
                'bands': bands}

    # header-vs-content disagreement signal (never used to slice)
    hdr_disagree = []
    for lab, ws in (hdr or {}).items():
        if lab not in labels:
            continue
        hx = sum(w.xc for w in ws) / len(ws)
        a, b = bands[labels[lab]]
        if not (a - 30 <= hx <= b + 30):
            hdr_disagree.append('%s hdr_x=%.1f band=%.1f-%.1f' % (lab, hx, a, b))
    if hdr_disagree:
        warn.append('HEADER_LABEL_OFFSET_MISMATCH:' + '; '.join(hdr_disagree))

    ci = labels['commission']

    # --- per-page row assembly on the commission spine
    lines = []
    for pi in sorted(body_by_page.keys()):
        bw = body_by_page[pi]
        if not bw:
            continue
        per_band = defaultdict(list)
        for w in bw:
            per_band[band_of(w, bands)].append(w)

        comm_cells = cells_in_band(per_band.get(ci, []))
        # spine = money-valued cells only
        spine = []
        for c in comm_cells:
            if len(c['tokens']) == 1 and looks_money(c['text']):
                spine.append(c)
            elif looks_money(c['text'].replace(' ', '')):
                spine.append(c)
            else:
                if c['text'].strip():
                    warn.append('P%d_NONMONEY_IN_COMMISSION_BAND:%s' % (pi + 1, c['text'][:40]))
        if not spine:
            continue
        spine_y = [c['y'] for c in spine]

        # median row pitch -> max attach distance
        if len(spine_y) >= 2:
            gaps = sorted(spine_y[i + 1] - spine_y[i] for i in range(len(spine_y) - 1))
            pitch = gaps[len(gaps) // 2]
        else:
            pitch = 14.0
        max_dy = max(4.0, min(pitch * 0.75, 12.0))

        attached = {}
        orphans = {}
        for lab, bi in labels.items():
            if bi == ci:
                continue
            cells = cells_in_band(per_band.get(bi, []))
            got, un = monotonic_align(spine_y, cells, max_dy)
            attached[lab] = got
            if un:
                orphans[lab] = [cells[k]['text'] for k in un]
        if orphans:
            for lab, texts in orphans.items():
                warn.append('P%d_ORPHAN_%s:%s' % (pi + 1, lab.upper(), '|'.join(t[:30] for t in texts)))

        for ri in range(len(spine)):
            amt = parse_money(spine[ri]['text'])
            if amt is None:
                continue
            def cell(lab):
                c = attached.get(lab, [None] * len(spine))[ri]
                return c['text'].strip() if c else ''
            policy = cell('policy')
            agent = cell('agent')
            company = cell('company')
            insured = cell('insured')
            split = cell('split')
            rate = cell('comp_rate')

            row_warn = []
            # strict classifier guards
            if rate and not looks_pct(rate):
                if looks_split(rate) and not split:
                    split, rate = rate, ''
                else:
                    row_warn.append('RATE_NOT_PERCENT:' + rate[:20])
            if split and not looks_split(split):
                row_warn.append('SPLIT_UNEXPECTED:' + split[:20])
            if policy and not looks_policy(policy):
                row_warn.append('POLICY_SHAPE:' + policy[:24])
            carrier = match_carrier(company, carrier_idx) if company else (default_carrier or '')
            if company and carrier_norm(carrier) != carrier_norm(company):
                row_warn.append('CARRIER_ALIAS:%s->%s' % (company[:28], carrier[:28]))

            lines.append({
                'policy_number': policy,
                'agent_name': agent,
                'insured_name': insured,
                'carrier': carrier or default_carrier or '',
                'split': split,
                'comp_rate': rate,
                'commission_amount': round(amt, 2),
                'paid_date': statement_date,
                'notes': '',
                '_prov': {
                    'page': pi + 1,
                    'row': ri + 1,
                    'y': round(spine[ri]['y'], 2),
                    'company_raw': company,
                    'warnings': row_warn,
                },
            })

    return {'ok': True, 'lines': lines, 'footer_total': footer_total,
            'warnings': warn, 'pages': npages, 'bands': bands,
            'labels': labels, 'fingerprints': fps}


# ---------------------------------------------------------------- footer, R9, driver

FOOTER_TEXT_RE = re.compile(
    r'total\s*(?:paid|due|commission)?\s*[:\-]?\s*\(?\s*-?\$?\s*-?[\d,]+(?:\.\d{1,2})?\s*\)?-?',
    re.I)


def footer_from_layout_text(path):
    """Independent footer read from `pdftotext -layout` (strategy 3)."""
    try:
        txt = subprocess.check_output(['pdftotext', '-layout', path, '-'],
                                      stderr=subprocess.DEVNULL).decode('utf-8', 'replace')
    except Exception:
        return None, ''
    best = None
    for ln in txt.splitlines():
        low = ln.lower()
        if 'total paid' in low or re.search(r'\btotal\b\s*:', low) or 'grand total' in low:
            toks = re.findall(r'\(?-?\$?-?[\d,]+(?:\.\d{1,2})?\)?-?', ln)
            vals = [parse_money(t) for t in toks]
            vals = [v for v in vals if v is not None]
            if vals:
                best = vals[-1]
    return best, txt


def r9_check(lines, footer_total):
    if footer_total is None:
        return {'status': 'NO_FOOTER', 'sum': round(sum(l['commission_amount'] for l in lines), 2),
                'footer': None, 'diff': None}
    s = round(sum(l['commission_amount'] for l in lines), 2)
    d = round(s - footer_total, 2)
    return {'status': 'PASS' if abs(d) < 0.005 else 'FAIL', 'sum': s,
            'footer': round(footer_total, 2), 'diff': d}


def carrier_rounding_repair(lines, footer, evidence):
    """
    Protocol §7: the carrier sometimes PRINTS a line rounded to whole dollars while
    computing Total Paid in true cents.  Repair ONLY against evidence -- another
    statement that reprints the same policy for the same agent with cents -- and only
    when the substitution closes R9 exactly.  Never adjusts Total Paid (R1).
    Returns (lines, notes).  `evidence` maps (POLICY, agent_lower) -> set(amounts).
    """
    notes = []
    if footer is None or not lines or not evidence:
        return lines, notes
    diff = round(sum(l['commission_amount'] for l in lines) - footer, 2)
    if abs(diff) < 0.005 or abs(diff) >= 1.00:
        return lines, notes

    cands = []
    for i, l in enumerate(lines):
        a = l['commission_amount']
        if abs(a - round(a)) > 0.0001:
            continue                      # printed with cents -> not a rounding victim
        key = ((l['policy_number'] or '').upper(), (l['agent_name'] or '').strip().lower())
        alts = set()
        for v in evidence.get(key, ()):
            if abs(v - a) < 0.0001:
                continue
            if abs(v - a) < 0.995 and round(v) == round(a):
                alts.add(round(v, 2))
        if alts:
            cands.append((i, a, sorted(alts)))
    if not cands:
        return lines, notes

    # search subsets of size 1..3
    import itertools
    sols = []
    for k in (1, 2, 3):
        if len(sols) or k > len(cands):
            break
        for combo in itertools.combinations(cands, k):
            for choice in itertools.product(*[c[2] for c in combo]):
                delta = sum(choice[j] - combo[j][1] for j in range(k))
                if abs(round(delta - diff * -1, 2)) < 0.005:
                    sols.append(list(zip([c[0] for c in combo], choice,
                                         [c[1] for c in combo])))
        if len(sols) > 1:
            sols = []                      # ambiguous at this size -> refuse
            break
    if len(sols) != 1:
        return lines, notes
    for idx, newv, oldv in sols[0]:
        lines[idx]['commission_amount'] = newv
        lines[idx]['_prov'].setdefault('warnings', []).append(
            'CARRIER_ROUNDING_REPAIR:%.2f->%.2f' % (oldv, newv))
        notes.append('CARRIER_ROUNDING_REPAIR %s %.2f->%.2f'
                     % (lines[idx]['policy_number'], oldv, newv))
    return lines, notes


def line_key(l):
    return (l['policy_number'].upper(), round(l['commission_amount'], 2))


def compare_strategies(a, b):
    """Return list of human-readable disagreements between two extraction results."""
    out = []
    if not a.get('ok') or not b.get('ok'):
        if a.get('ok') != b.get('ok'):
            out.append('OK_MISMATCH:%s/%s' % (a.get('ok'), b.get('ok')))
        return out
    la, lb = a['lines'], b['lines']
    if len(la) != len(lb):
        out.append('LINE_COUNT:%d vs %d' % (len(la), len(lb)))
    sa = round(sum(x['commission_amount'] for x in la), 2)
    sb = round(sum(x['commission_amount'] for x in lb), 2)
    if abs(sa - sb) >= 0.005:
        out.append('SUM:%.2f vs %.2f' % (sa, sb))
    fa, fb = a.get('footer_total'), b.get('footer_total')
    if (fa is None) != (fb is None) or (fa is not None and abs(fa - fb) >= 0.005):
        out.append('FOOTER:%s vs %s' % (fa, fb))
    ka = defaultdict(int); kb = defaultdict(int)
    for x in la: ka[line_key(x)] += 1
    for x in lb: kb[line_key(x)] += 1
    for k in set(ka) | set(kb):
        if ka[k] != kb[k]:
            out.append('ROW %s:%s x%d vs x%d' % (k[0], ('%.2f' % k[1]), ka[k], kb[k]))
    # agent-name disagreements on rows that match by key
    ia = {line_key(x): x for x in la}
    ib = {line_key(x): x for x in lb}
    for k in set(ia) & set(ib):
        na = (ia[k]['agent_name'] or '').strip().lower()
        nb = (ib[k]['agent_name'] or '').strip().lower()
        if na != nb:
            out.append('AGENT %s:%r vs %r' % (k[0], ia[k]['agent_name'], ib[k]['agent_name']))
    return out[:40]


def deterministic_line_id(statement_id, file_sha, line):
    """Collision-proof: hash of statement + file + row identity. No LINE-nnnnnn counters."""
    base = '|'.join([
        str(statement_id or ''), str(file_sha or '')[:16],
        str(line.get('_prov', {}).get('page', '')),
        str(line.get('_prov', {}).get('row', '')),
        (line.get('policy_number') or '').upper(),
        '%.2f' % float(line.get('commission_amount') or 0.0),
        (line.get('agent_name') or '').strip().upper(),
    ])
    return 'GL-' + hashlib.sha1(base.encode('utf-8')).hexdigest()[:20].upper()


def load_evidence(path):
    """policy|agent -> [amounts]  (JSON produced by build_evidence.py from the corpus
    or from statement_lines).  Used only by the §7 evidenced rounding repair."""
    if not path or not os.path.exists(path):
        return {}
    try:
        raw = json.load(open(path))
    except Exception:
        return {}
    out = {}
    for k, v in raw.items():
        pol, _, ag = k.partition('|')
        out[(pol.upper(), ag.strip().lower())] = set(float(x) for x in v)
    return out


def extract(path, statement_id='', statement_date='', default_carrier='',
            carriers_path='/home/litcrm/public_html/data/carriers.json',
            want_ocr=False, evidence=None):
    carrier_names = load_carriers(carriers_path)
    cidx = build_carrier_index(carrier_names)

    res = {'version': VERSION, 'file': path, 'statement_id': statement_id,
           'strategies': {}, 'warnings': [], 'disagreements': []}

    try:
        with open(path, 'rb') as fh:
            res['file_sha256'] = hashlib.sha256(fh.read()).hexdigest()
    except Exception:
        res['file_sha256'] = ''

    w1, d1 = words_pdfplumber(path)
    w2, d2 = words_poppler_bbox(path)

    s1 = extract_with_words(w1, d1, cidx, statement_date, default_carrier)
    s2 = extract_with_words(w2, d2, cidx, statement_date, default_carrier)
    res['strategies']['pdfplumber'] = {'ok': s1.get('ok'), 'lines': len(s1.get('lines') or []),
                                       'footer': s1.get('footer_total'),
                                       'warnings': s1.get('warnings') or []}
    res['strategies']['poppler_bbox'] = {'ok': s2.get('ok'), 'lines': len(s2.get('lines') or []),
                                         'footer': s2.get('footer_total'),
                                         'warnings': s2.get('warnings') or []}

    f3, layout_text = footer_from_layout_text(path)
    res['strategies']['pdftotext_layout'] = {'footer': f3}

    s4 = None
    total_words = len(w1) + len(w2)
    if want_ocr or total_words < 20:
        w4, d4 = words_ocr(path)
        s4 = extract_with_words(w4, d4, cidx, statement_date, default_carrier)
        res['strategies']['ocr'] = {'ok': s4.get('ok'), 'lines': len(s4.get('lines') or []),
                                    'footer': s4.get('footer_total')}

    # --- choose primary
    order = [('pdfplumber', s1), ('poppler_bbox', s2)]
    if s4 is not None:
        order.append(('ocr', s4))

    footer_candidates = [x for x in [s1.get('footer_total'), s2.get('footer_total'), f3]
                         if x is not None]
    footer = None
    if footer_candidates:
        # majority vote to the cent
        cnt = defaultdict(int)
        for v in footer_candidates:
            cnt[round(v, 2)] += 1
        footer = max(cnt.items(), key=lambda kv: (kv[1], -abs(kv[0])))[0]
        if len(cnt) > 1:
            res['warnings'].append('FOOTER_DISAGREE:' + ','.join('%.2f' % k for k in cnt))

    scored = []
    for name, s in order:
        if not s or not s.get('ok') or not s.get('lines'):
            continue
        chk = r9_check(s['lines'], footer)
        scored.append((0 if chk['status'] == 'PASS' else 1,
                       abs(chk['diff']) if chk['diff'] is not None else 9e9,
                       -len(s['lines']), name, s, chk))
    scored.sort(key=lambda t: (t[0], t[1], t[2]))

    if not scored:
        res['ok'] = False
        res['lines'] = []
        res['footer_total'] = footer
        res['r9'] = r9_check([], footer)
        res['warnings'].append('ALL_STRATEGIES_EMPTY')
        return res

    _, _, _, winner, best, chk = scored[0]
    res['ok'] = True
    res['primary_strategy'] = winner
    res['footer_total'] = footer
    res['pages'] = best.get('pages')
    res['bands'] = best.get('bands')
    res['labels'] = best.get('labels')
    res['warnings'].extend(best.get('warnings') or [])

    # cross-validation
    if s1.get('ok') and s2.get('ok'):
        res['disagreements'] = compare_strategies(s1, s2)
    agree = (not res['disagreements'])

    lines = best['lines']
    # --- footer-value guard (belt AND braces with the positional exclusion)
    if footer is not None:
        kept = []
        for l in lines:
            if (abs(l['commission_amount'] - footer) < 0.005 and not l['policy_number']
                    and not l['agent_name']):
                res['warnings'].append('DROPPED_FOOTER_AS_LINE:%.2f' % footer)
                continue
            kept.append(l)
        lines = kept

    chk = r9_check(lines, footer)
    if chk['status'] == 'FAIL' and evidence:
        lines, notes = carrier_rounding_repair(lines, footer, evidence)
        if notes:
            res['warnings'].extend(notes)
            chk = r9_check(lines, footer)
    res['r9'] = chk
    if chk['status'] == 'FAIL':
        res['warnings'].append('R9_FAIL diff=%.2f' % chk['diff'])

    for i, l in enumerate(lines):
        l['_prov']['strategy'] = winner
        l['_prov']['strategies_agree'] = agree
        l['_prov']['confidence'] = round(
            (0.55 if chk['status'] == 'PASS' else 0.25)
            + (0.25 if agree else 0.0)
            + (0.10 if l['policy_number'] else 0.0)
            + (0.10 if l['agent_name'] else 0.0), 3)
        l['line_uid'] = deterministic_line_id(statement_id, res['file_sha256'], l)
    res['lines'] = lines
    return res


def main():
    args = [a for a in sys.argv[1:]]
    if not args:
        print(__doc__); return 2
    ev = {}
    if '--evidence' in args:
        ev = load_evidence(args[args.index('--evidence') + 1])
    if args[0] == '--batch':
        with open(args[1]) as fh:
            paths = [ln.strip() for ln in fh if ln.strip()]
        for p in paths:
            sid = os.path.basename(p).split('_')[0]
            try:
                r = extract(p, statement_id=sid, evidence=ev)
            except Exception as e:
                r = {'file': p, 'statement_id': sid, 'ok': False,
                     'error': '%s: %s' % (type(e).__name__, e), 'lines': [],
                     'r9': {'status': 'ERROR'}}
            sys.stdout.write(json.dumps(r) + '\n')
            sys.stdout.flush()
        return 0
    path = args[0]

    def optval(flag, default=''):
        if flag in args:
            i = args.index(flag)
            if i + 1 < len(args):
                return args[i + 1]
        return default

    sid = optval('--statement-id') or os.path.basename(path).split('_')[0]
    r = extract(path, statement_id=sid,
                statement_date=optval('--statement-date'),
                default_carrier=optval('--default-carrier'),
                want_ocr=('--ocr' in args), evidence=ev)
    if '--json' in args:
        print(json.dumps(r, indent=2))
    else:
        print('file      :', r['file'])
        print('strategy  :', r.get('primary_strategy'))
        print('pages     :', r.get('pages'))
        print('bands     :', r.get('bands'))
        print('labels    :', r.get('labels'))
        print('footer    :', r.get('footer_total'))
        print('R9        :', r.get('r9'))
        print('warnings  :', r.get('warnings')[:12])
        print('disagree  :', r.get('disagreements')[:12])
        print('--- %d lines ---' % len(r.get('lines') or []))
        for l in (r.get('lines') or []):
            print('%-26s %-26s %-14s %-26s %-5s %-8s %10.2f  %s' % (
                l['agent_name'][:26], l['carrier'][:26], l['policy_number'][:14],
                l['insured_name'][:26], l['split'], l['comp_rate'],
                l['commission_amount'], ','.join(l['_prov']['warnings'])))
    return 0


if __name__ == '__main__':
    sys.exit(main())
