"""Retained item9_bench_segment.py research algorithms. Use analysis.py for portable CLI; see README and provenance."""
import os, sys, csv, json, argparse, re, datetime as dt
import numpy as np, cv2
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
HERE = os.path.dirname(os.path.abspath(__file__))
import item9_seed_crosstab as I
LANE = os.path.dirname(os.path.abspath(__file__))
OUT = ''
SEED = I.SEED
SRC = I.SRC
PARAMS = dict(ink_k=0.45, wide=1.6, min_area_frac=0.05, shaft_h=1.45, shaft_max_wh=0.8, shaft_max_holes=1, gap_tol=0.25, partner_h=1.2, partner_max_holes=1, flat_h=0.75, flat_lo=0.2, flat_hi=1.1, lo_frac=0.55, pad_x=0.5, pad_y=0.15, overlap_max=0.2, max_group=4, bar_band=(0.3, 0.85), bar_min_run=0.55, bar_min_w=0.85, bar_min_rows=1, loop_floor_rows=3, union_h=1.65, max_fill=0.33, shaft_run=0.6, bar_min_abs=0.7, below_frac=0.12)

def ensure(p):
    os.makedirs(p, exist_ok=True)
    return p

def sidecar(cmd, args):
    ts = dt.datetime.now().strftime('%Y%m%dT%H%M%S')
    json.dump({'script': 'item9_bench_segment.py', 'cmd': cmd, 'argv': sys.argv[1:], 'args': args, 'params': PARAMS, 'seed': SEED, 'time': ts}, open(os.path.join(ensure(OUT), 'run_args_%s_%s.json' % (cmd, ts)), 'w'), indent=1)

def segment_comp(prm=PARAMS, dmaps=None):
    pieces = []
    for fol, (path, sc, boxes) in SRC.items():
        rgb = np.array(Image.open(path).convert('RGB'))
        gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
        raw = []
        for bi, (bx0, by0, bx1, by1) in enumerate(boxes):
            x0, y0, x1, y1 = [int(round(v * sc)) for v in (bx0, by0, bx1, by1)]
            g = gray[y0:y1, x0:x1]
            c = rgb[y0:y1, x0:x1].astype(np.int32)
            d = np.clip(cv2.GaussianBlur(g, (0, 0), 25) - g, 0, None)
            thr = max(14.0, prm['ink_k'] * np.percentile(d, 98))
            ink = (d > thr).astype(np.uint8)
            red = c[..., 0] - c[..., 1] > 55
            red = cv2.dilate(red.astype(np.uint8), np.ones((9, 9), np.uint8)) > 0
            ink[red] = 0
            if dmaps is not None:
                dmaps[fol, bi] = (d, thr, red, x0, y0)
            ink = cv2.morphologyEx(ink, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
            n, lab, st, ce = cv2.connectedComponentsWithStats(ink, connectivity=8)
            for i in range(1, n):
                x, y, w, h, ar = st[i]
                raw.append((x0 + x, y0 + y, w, h, ar, (lab[y:y + h, x:x + w] == i).astype(np.uint8), bi))
        hs = np.array([r[3] for r in raw if r[4] > 40])
        med_h = float(np.median(hs))
        amin = prm['min_area_frac'] * med_h * med_h
        for ci, (x, y, w, h, ar, m, bi) in enumerate(raw):
            if ar < amin or h < 0.35 * med_h or h > 4.0 * med_h:
                continue
            xo = x
            for pm, dx, dy in I.split_wide(m, med_h, prm['wide']):
                if pm.sum() < amin:
                    continue
                pieces.append(dict(src=fol, box=bi, comp=ci, mask=pm, x=x + dx, y=y + dy, x_csv=xo, y_csv=y, w=pm.shape[1], h=pm.shape[0], med_h=med_h))
                xo += pm.shape[1]
    return pieces

def n_holes(m):
    cs, hier = cv2.findContours(np.pad(m, 1).astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    if hier is None:
        return 0
    return int(sum((1 for hh, c in zip(hier[0], cs) if hh[3] >= 0 and cv2.contourArea(c) >= 3)))

def filled_holes(m):
    """Mask of enclosed background (holes) of m."""
    p = np.pad(m, 1).astype(np.uint8)
    ff = p.copy()
    h, w = ff.shape
    mask = np.zeros((h + 2, w + 2), np.uint8)
    cv2.floodFill(ff, mask, (0, 0), 2)
    return ff[1:-1, 1:-1] == 0

def union_mask(group):
    x0 = min((p['x'] for p in group))
    y0 = min((p['y'] for p in group))
    x1 = max((p['x'] + p['w'] for p in group))
    y1 = max((p['y'] + p['h'] for p in group))
    m = np.zeros((y1 - y0, x1 - x0), np.uint8)
    for p in group:
        m[p['y'] - y0:p['y'] - y0 + p['h'], p['x'] - x0:p['x'] - x0 + p['w']] |= p['mask']
    return (m, x0, y0)

def runs_max(row):
    best = run = 0
    for v in row:
        run = run + 1 if v else 0
        if run > best:
            best = run
    return best

def col_runs(m):
    """Longest vertical run of ink per column."""
    h, w = m.shape
    out = np.zeros(w, int)
    cur = np.zeros(w, int)
    for y in range(h):
        cur = np.where(m[y] > 0, cur + 1, 0)
        out = np.maximum(out, cur)
    return out

def bar_test(m, med_h, prm, single):
    """Returns (ok, n_bar_rows, best_run_frac, bar_row_frac). m is the union mask. A bench needs (1) a straight shaft, a column
    whose longest vertical run is at least shaft_run x the union height, (2) a bar row in the bar band whose longest run is at
    least bar_min_run x the union width and at least bar_min_abs x the median height, that contains a shaft column, (3) shaft
    ink continuing below the bar for at least below_frac x the height, and (4) the bar row is not the floor of a closed loop."""
    h, w = m.shape
    if w < prm['bar_min_w'] * med_h or h < prm['union_h'] * med_h or m.mean() > prm['max_fill']:
        return (False, 0, 0.0, 0.0)
    cr = col_runs(m)
    shaft_cols = cr >= prm['shaft_run'] * h
    if not shaft_cols.any():
        return (False, 0, 0.0, 0.0)
    ho = filled_holes(m)
    lo, hi = (int(round(prm['bar_band'][0] * h)), int(round(prm['bar_band'][1] * h)))
    need = max(prm['bar_min_run'] * w, prm['bar_min_abs'] * med_h)
    nb, best, brow = (0, 0.0, 0.0)
    for y in range(lo, min(h, hi + 1)):
        row = m[y]
        run = 0
        bestrun = 0
        ok_row = False
        for x in range(w + 1):
            if x < w and row[x]:
                run += 1
            else:
                if run:
                    bestrun = max(bestrun, run)
                    if run >= need and shaft_cols[x - run:x].any():
                        ok_row = True
                run = 0
        if bestrun / w > best:
            best, brow = (bestrun / w, y / h)
        if not ok_row:
            continue
        if ho[max(0, y - prm['loop_floor_rows']):y].any():
            continue
        below = m[y + 2:min(h, y + 2 + max(2, int(prm['below_frac'] * h)))]
        if len(below) < max(2, int(prm['below_frac'] * h)) or not below.any(1).all():
            continue
        nb += 1
    return (nb >= prm['bar_min_rows'], nb, best, brow)

def enhance(group_mask, x0, y0, mh, dm, prm):
    """Faint-bar recovery. Re-threshold the darkness map of the group's neighbourhood at lo_frac x the item 9 threshold, close it
    3x3, and keep the low-threshold ink 8-connected to the group's own mask, clipped to the group's x extent plus or minus
    pad_x x median height and its y extent plus or minus pad_y x median height. Returns (mask, x, y) cropped to its ink."""
    d, thr, red, bx0, by0 = dm
    gh, gw = group_mask.shape
    px, py = (int(round(prm['pad_x'] * mh)), int(round(prm['pad_y'] * mh)))
    X0, X1 = (max(bx0, x0 - px), min(bx0 + d.shape[1], x0 + gw + px))
    Y0, Y1 = (max(by0, y0 - py), min(by0 + d.shape[0], y0 + gh + py))
    low = (d[Y0 - by0:Y1 - by0, X0 - bx0:X1 - bx0] > prm['lo_frac'] * thr).astype(np.uint8)
    low[red[Y0 - by0:Y1 - by0, X0 - bx0:X1 - bx0]] = 0
    seed = np.zeros_like(low)
    seed[y0 - Y0:y0 - Y0 + gh, x0 - X0:x0 - X0 + gw] = group_mask
    low |= seed
    low = cv2.morphologyEx(low, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
    n, lab = cv2.connectedComponents(low, connectivity=8)
    keep = np.unique(lab[(seed > 0) & (lab > 0)])
    out = np.isin(lab, keep).astype(np.uint8)
    ys, xs = np.nonzero(out)
    return (out[ys.min():ys.max() + 1, xs.min():xs.max() + 1], X0 + xs.min(), Y0 + ys.min())

def merge_pieces(ps, prm=PARAMS, dmaps=None):
    """Group parts into benched gallows. Returns (pieces after merging, merged-group records). Pieces keep a 'kind':
    'item9' (unchanged), 'bench_merged' (parts joined) or 'bench_single' (one piece that already holds a bench)."""
    for k, p in enumerate(ps):
        p['idx'] = k
        p['holes'] = n_holes(p['mask'])
    used = set()
    groups = []
    by_comp = {}
    for p in ps:
        by_comp.setdefault((p['src'], p['comp']), []).append(p)
    for key in sorted(by_comp):
        parts = sorted(by_comp[key], key=lambda q: q['x'])
        mh = parts[0]['med_h']
        for s in parts:
            if s['idx'] in used:
                continue
            if not (s['h'] >= prm['shaft_h'] * mh and s['w'] <= prm['shaft_max_wh'] * s['h'] and (s['holes'] <= prm['shaft_max_holes'])):
                continue
            grp = [s]
            changed = True
            while changed and len(grp) < prm['max_group']:
                changed = False
                gx0 = min((q['x'] for q in grp))
                gx1 = max((q['x'] + q['w'] for q in grp))
                for q in parts:
                    if q['idx'] in {g_['idx'] for g_ in grp} or q['idx'] in used:
                        continue
                    gap = max(q['x'] - gx1, gx0 - (q['x'] + q['w']))
                    if gap > prm['gap_tol'] * mh:
                        continue
                    tallq = q['h'] >= prm['partner_h'] * mh and q['holes'] <= prm['partner_max_holes']
                    cyf = (q['y'] + q['h'] / 2 - s['y']) / s['h']
                    flatq = q['h'] <= prm['flat_h'] * mh and q['holes'] == 0 and (prm['flat_lo'] <= cyf <= prm['flat_hi'])
                    if tallq or flatq:
                        grp.append(q)
                        changed = True
                        break
            m, x0, y0 = union_mask(grp)
            ok, nb, best, brow = bar_test(m, mh, prm, single=len(grp) == 1)
            enh = False
            if not ok and dmaps is not None and (prm['lo_frac'] > 0):
                m2, x2, y2 = enhance(m, x0, y0, mh, dmaps[s['src'], s['box']], prm)
                ok, nb, best, brow = bar_test(m2, mh, prm, single=len(grp) == 1)
                if ok:
                    m, x0, y0, enh = (m2, x2, y2, True)
            if ok:
                for q in grp:
                    used.add(q['idx'])
                groups.append(dict(parts=grp, mask=m, x=x0, y=y0, nbar=nb, bar_frac=best, bar_row=brow, enh=enh))

    def box(g):
        return (g['x'], g['y'], g['x'] + g['mask'].shape[1], g['y'] + g['mask'].shape[0])
    kept_g = []
    n_drop = 0
    for g in sorted(groups, key=lambda g: g['enh']):
        b = box(g)
        bad = False
        for k in kept_g:
            c = box(k)
            iw = min(b[2], c[2]) - max(b[0], c[0])
            ih = min(b[3], c[3]) - max(b[1], c[1])
            if iw > 0 and ih > 0 and (iw * ih > prm['overlap_max'] * min((b[2] - b[0]) * (b[3] - b[1]), (c[2] - c[0]) * (c[3] - c[1]))):
                bad = True
                break
        if bad:
            n_drop += 1
        else:
            kept_g.append(g)
    groups = kept_g
    prm['_dropped_overlap'] = n_drop
    out = []
    gid = {}
    for gi, g in enumerate(groups):
        for q in g['parts']:
            gid[q['idx']] = gi
    done = set()
    for p in ps:
        if p['idx'] in gid:
            gi = gid[p['idx']]
            if gi in done:
                continue
            done.add(gi)
            g = groups[gi]
            f = g['parts'][0]
            out.append(dict(src=f['src'], box=f['box'], comp=f['comp'], mask=g['mask'], x=g['x'], y=g['y'], w=g['mask'].shape[1], h=g['mask'].shape[0], med_h=f['med_h'], kind=('bench_merged' if len(g['parts']) > 1 else 'bench_single') + ('_enh' if g['enh'] else ''), n_parts=len(g['parts']), parts=[q['idx'] for q in g['parts']], bar_frac=g['bar_frac'], bar_row=g['bar_row'], holes=n_holes(g['mask'])))
        else:
            out.append(dict(src=p['src'], box=p['box'], comp=p['comp'], mask=p['mask'], x=p['x'], y=p['y'], w=p['w'], h=p['h'], med_h=p['med_h'], kind='item9', n_parts=1, parts=[p['idx']], bar_frac=0.0, bar_row=0.0, holes=p['holes']))
    return (out, groups)

def check_against_item9(ps):
    cl = [r for r in I.load_clusters() if r['source'] != 'f57v.3']
    assert len(ps) == len(cl), 'piece count differs from clusters.csv: %d vs %d' % (len(ps), len(cl))
    for p, r in zip(ps, cl):
        assert p['src'] == r['source'] and p['w'] == int(r['w_px']) and (p['h'] == int(r['h_px'])) and (p['x_csv'] == int(r['x'])) and (p['y_csv'] == int(r['y'])), (p, r)
    return len(cl)

def cmd_segment(a):
    dmaps = {}
    ps = segment_comp(dmaps=dmaps)
    n = check_against_item9(ps)
    print('item 9 replica matches clusters.csv for %d text-folio pieces' % n)
    out, groups = merge_pieces(ps, dmaps=dmaps)
    ensure(OUT)
    nm = sum((1 for o in out if o['kind'].startswith('bench_merged')))
    ns = sum((1 for o in out if o['kind'].startswith('bench_single')))
    print('groups dropped as overlapping a kept group: %d' % PARAMS.pop('_dropped_overlap', 0))
    ne = sum((1 for o in out if o['kind'].endswith('_enh')))
    print('of which faint-bar recovered (low-threshold mask) %d' % ne)
    print('pieces before %d, after %d; merged groups %d (parts joined), single-piece benches %d' % (len(ps), len(out), nm, ns))
    for f in SRC:
        print('  %s: merged %d, single %d' % (f, sum((1 for o in out if o['src'] == f and o['kind'].startswith('bench_merged'))), sum((1 for o in out if o['src'] == f and o['kind'].startswith('bench_single')))))
    with open(os.path.join(OUT, 'pieces_c.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['pid', 'source', 'box', 'comp', 'x', 'y', 'w_px', 'h_px', 'h_norm', 'w_norm', 'holes', 'kind', 'n_parts', 'item9_parts', 'bar_frac', 'bar_row'])
        for k, o in enumerate(out):
            o['pid'] = k
            w.writerow([k, o['src'], o['box'], o['comp'], o['x'], o['y'], o['w'], o['h'], round(o['h'] / o['med_h'], 3), round(o['w'] / o['med_h'], 3), o['holes'], o['kind'], o['n_parts'], ' '.join(map(str, o['parts'])), round(o['bar_frac'], 3), round(o['bar_row'], 3)])
    np.savez_compressed(os.path.join(OUT, 'pieces_c.npz'), **{'p%d' % o['pid']: o['mask'] for o in out})
    with open(os.path.join(OUT, 'merged.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['pid', 'source', 'kind', 'n_parts', 'x', 'y', 'w_px', 'h_px'])
        for o in out:
            if o['kind'] != 'item9':
                w.writerow([o['pid'], o['src'], o['kind'], o['n_parts'], o['x'], o['y'], o['w'], o['h']])
    for fol in SRC:
        im = np.array(Image.open(SRC[fol][0]).convert('RGB'))
        P = [o for o in out if o['src'] == fol]
        for o in P:
            if o['kind'] != 'item9':
                cv2.rectangle(im, (o['x'] - 2, o['y'] - 2), (o['x'] + o['w'] + 2, o['y'] + o['h'] + 2), (255, 0, 0), 3)
        x0 = min((o['x'] for o in P)) - 40
        x1 = max((o['x'] + o['w'] for o in P)) + 40
        y0 = min((o['y'] for o in P)) - 40
        y1 = max((o['y'] + o['h'] for o in P)) + 40
        c = im[max(0, y0):y1, max(0, x0):x1]
        s = 2400 / max(c.shape[:2])
        Image.fromarray(cv2.resize(c, None, fx=s, fy=s, interpolation=cv2.INTER_AREA)).save(os.path.join(OUT, 'overlay_%s.png' % fol))

def load_pieces():
    rows = list(csv.DictReader(open(os.path.join(OUT, 'pieces_c.csv'))))
    z = np.load(os.path.join(OUT, 'pieces_c.npz'))
    P = []
    for r in rows:
        d = dict(pid=int(r['pid']), source=r['source'], box=int(r['box']), comp=int(r['comp']), x=int(r['x']), y=int(r['y']), w_px=int(r['w_px']), h_px=int(r['h_px']), h_norm=float(r['h_norm']), w_norm=float(r['w_norm']), holes=int(r['holes']), kind=r['kind'], n_parts=int(r['n_parts']), mask=z['p%s' % r['pid']])
        d['med_h'] = d['h_px'] / d['h_norm']
        P.append(d)
    return P

def line_assign(P):
    """9b rows: fit_rows on the item 9 (pre-merge) pieces of each box, exactly as 9b build_lines did, then assign pieces
    (merged or not) to those rows. Returns rows (kept records with EVA counts), {pid: (row key, ok)}, status."""
    g9 = I.load_geom()
    rows, status = I.build_lines(g9)[0::2]
    prow = {}
    for fol in ('f1r', 'f49v', 'f88r'):
        path, sc, boxes = SRC[fol]
        for b in range(len(boxes)):
            Pb9 = [p for p in g9 if p['source'] == fol and p['box'] == b]
            L, ang = I.fit_rows(Pb9, I.SPACING[fol])
            sp = float(np.median(np.diff([aa + bb * 1500 for aa, bb in L]))) if len(L) > 1 else I.SPACING[fol]
            Pb = [p for p in P if p['source'] == fol and p['box'] == b]
            Q = [dict(x=p['x'], y=p['y'], w_px=p['w_px'], h_px=p['h_px'], h_norm=p['h_norm'], med_h=p['med_h'], pid=p['pid']) for p in Pb]
            I.assign_lines(Q, L)
            for q in Q:
                cx = q['x'] + q['w_px'] / 2
                prow[q['pid']] = ((fol, b, q['row']), q['row_dist'] <= 0.45 * sp and cx <= I.XMAX.get(fol, 1000000000.0))
    return (rows, prow, status)

def cmd_measure(a):
    rng = np.random.default_rng(SEED)
    log = []

    def say(*x):
        line = ' '.join((str(v) for v in x))
        print(line)
        log.append(line)
    P = load_pieces()
    rows, prow, status = line_assign(P)
    kept = [r for r in rows if r['kept']]
    key = {(r['folio'], r['box'], r['row']): n for n, r in enumerate(kept)}
    for r in kept:
        r['gallows_all'] = r['k'] + r['t'] + r['p'] + r['f'] + r['bench']
        r['g_ch'] = len(re.findall('(?<!c)[ktpf](?=ch|sh)', r['eva']))
        r['bench_or_g_ch'] = r['bench'] + r['g_ch']
    shape_vars = ['benched', 'benched_merged', 'benched_single', 'plain_shaft', 'item9_pieces', 'pieces_c']
    Xs = np.zeros((len(kept), len(shape_vars)))
    for p in P:
        rk, ok = prow[p['pid']]
        n = key.get(rk)
        if n is None or not ok:
            continue
        Xs[n, 5] += 1
        if p['kind'] != 'item9':
            Xs[n, 0] += 1
            Xs[n, 1 if p['kind'].startswith('bench_merged') else 2] += 1
        else:
            if p['h_norm'] >= PARAMS['shaft_h'] and p['w_px'] <= PARAMS['shaft_max_wh'] * p['h_px'] and (p['holes'] <= PARAMS['shaft_max_holes']):
                Xs[n, 3] += 1
            Xs[n, 4] += 1
    Ye = np.array([[r[c] for c in I.EVA_X] for r in kept], float)
    grp = [r['folio'] for r in kept]
    with open(os.path.join(OUT, 'measure_line_counts.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['folio', 'box', 'row', 'zl_lines'] + shape_vars + ['eva:' + c for c in I.EVA_X])
        for n, r in enumerate(kept):
            w.writerow([r['folio'], r['box'], r['row'], r['zl_lines']] + [int(v) for v in Xs[n]] + [int(v) for v in Ye[n]])
    say('lines kept', len(kept), json.dumps({f_: s_['kept'] for f_, s_ in status.items()}))
    folios = sorted(set(grp))
    gi = {f_: np.where(np.array(grp) == f_)[0] for f_ in folios}
    res = {'params': PARAMS, 'seed': SEED, 'perms': a.perms, 'lines_status': status}
    tot = {}
    for f_ in folios + ['all']:
        m = np.arange(len(kept)) if f_ == 'all' else gi[f_]
        tot[f_] = dict(lines=len(m), benched=int(Xs[m, 0].sum()), merged=int(Xs[m, 1].sum()), single=int(Xs[m, 2].sum()), eva_bench=int(Ye[m, I.EVA_X.index('bench')].sum()), eva_g_ch=int(Ye[m, I.EVA_X.index('g_ch')].sum()), eva_plain_gallows=int(sum((Ye[m, I.EVA_X.index(c)].sum() for c in 'ktpf'))), plain_shaft=int(Xs[m, 3].sum()), pieces=int(Xs[m, 5].sum()), eva_units=int(Ye[m, I.EVA_X.index('units')].sum()))
        t = tot[f_]
        t['overcount_ratio'] = t['benched'] / t['eva_bench'] if t['eva_bench'] else None
        say('%s: lines %d, benched %d (merged %d, single %d) vs EVA bench %d -> ratio %.2f; plain shaft pieces %d vs EVA k+t+p+f %d; pieces %d vs units %d' % (f_, t['lines'], t['benched'], t['merged'], t['single'], t['eva_bench'], t['overcount_ratio'] or float('nan'), t['plain_shaft'], t['eva_plain_gallows'], t['pieces'], t['eva_units']))
    res['totals'] = tot
    units = Ye[:, I.EVA_X.index('units')]
    Xc = np.stack([I.within(Xs[:, j], grp) for j in range(Xs.shape[1])], 1)
    Yc = np.stack([I.within(Ye[:, j], grp) for j in range(Ye.shape[1])], 1)
    Xr = np.stack([I.resid(Xs[:, j], units, grp) for j in range(Xs.shape[1])], 1)
    Yr = np.stack([I.resid(Ye[:, j], units, grp) for j in range(Ye.shape[1])], 1)
    R = I.corr_cols(Xc, Yc)
    Rp = I.corr_cols(Xr, Yr)
    ge = np.zeros_like(R)
    gep = np.zeros_like(R)
    for _ in range(a.perms):
        perm = np.arange(len(kept))
        for f_ in folios:
            perm[gi[f_]] = rng.permutation(gi[f_])
        ge += np.abs(I.corr_cols(Xc[perm], Yc)) >= np.abs(R) - 1e-12
        gep += np.abs(I.corr_cols(Xr[perm], Yr)) >= np.abs(Rp) - 1e-12
    P_ = (ge + 1) / (a.perms + 1)
    Pp = (gep + 1) / (a.perms + 1)
    for name, M in (('r', R), ('p', P_), ('partial_r', Rp), ('partial_p', Pp)):
        with open(os.path.join(OUT, 'measure_matrix_%s.csv' % name), 'w', newline='') as f:
            w = csv.writer(f)
            w.writerow(['shape'] + I.EVA_X)
            for j, v in enumerate(shape_vars):
                w.writerow([v] + ['%.4f' % x if np.isfinite(x) else '' for x in M[j]])

    def cell(v, c):
        j = shape_vars.index(v)
        e = I.EVA_X.index(c)
        return dict(r=float(R[j, e]), p=float(P_[j, e]), partial_r=float(Rp[j, e]), partial_p=float(Pp[j, e]))
    controls = ['d', 'ch', 'sh', 'k', 't', 'p', 'f', 'l', 'o', 'y']
    pred = {}
    for v, target in (('benched', 'bench'), ('benched_merged', 'bench'), ('benched_single', 'bench'), ('benched', 'bench_or_g_ch'), ('benched', 'gallows_all'), ('plain_shaft', 'bench'), ('plain_shaft', 'gallows_all'), ('benched', 'g_ch')):
        d_ = cell(v, target)
        d_['controls'] = {c: cell(v, c) for c in controls if c != target}
        pred['%s ~ %s' % (v, target)] = d_
        say('%-15s ~ %-14s r=%.3f p=%.4f | partial r=%.3f p=%.4f | controls partial r: %s' % (v, target, d_['r'], d_['p'], d_['partial_r'], d_['partial_p'], ' '.join(('%s %.2f' % (c, x['partial_r']) for c, x in d_['controls'].items()))))
    res['predictions'] = pred
    pf = {}
    for f_ in folios:
        m = gi[f_]
        for v, target in (('benched', 'bench'), ('benched', 'bench_or_g_ch')):
            x = Xs[m, shape_vars.index(v)]
            y = Ye[m, I.EVA_X.index(target)]
            rr = float(np.corrcoef(x, y)[0, 1]) if x.std() > 0 and y.std() > 0 else float('nan')
            pf['%s %s~%s' % (f_, v, target)] = dict(n_lines=len(m), r=rr, shape_total=int(x.sum()), eva_total=int(y.sum()))
            say('  %s %s ~ %s: n=%d r=%.3f totals %d vs %d' % (f_, v, target, len(m), rr, x.sum(), y.sum()))
    res['per_folio'] = pf
    lofo = {}
    j = shape_vars.index('benched')
    e = I.EVA_X.index('bench')
    for f_ in folios:
        m = np.array([gg != f_ for gg in grp])
        gm = [gg for gg in grp if gg != f_]
        x = I.within(Xs[m, j], gm)
        y = I.within(Ye[m, e], gm)
        r0 = float(np.corrcoef(x, y)[0, 1])
        ii = {h: np.where(np.array(gm) == h)[0] for h in set(gm)}
        c = 0
        for _ in range(2000):
            pm = np.arange(len(gm))
            for h in sorted(ii):
                pm[ii[h]] = rng.permutation(ii[h])
            c += abs(np.corrcoef(x[pm], y)[0, 1]) >= abs(r0) - 1e-12
        lofo['benched~bench without %s' % f_] = dict(n=int(m.sum()), r=r0, p=(c + 1) / 2001)
        say('  LOFO benched ~ bench without %s: n=%d r=%.3f p=%.4f' % (f_, m.sum(), r0, (c + 1) / 2001))
    res['leave_one_folio_out'] = lofo
    json.dump(res, open(os.path.join(OUT, 'measure.json'), 'w'), indent=1, default=float)
    open(os.path.join(OUT, 'measure_stdout.txt'), 'w').write('\n'.join(log) + '\n')

def tile_for(p, imgs, T, S_ctx=0.75):
    g = imgs[p['source']]
    mh = p['med_h']
    cx, cy = (p['x'] + p['w_px'] / 2, p['y'] + p['h_px'] / 2)
    half = max(p['w_px'], p['h_px']) / 2 + S_ctx * mh
    x0, x1 = (int(cx - half), int(cx + half))
    y0, y1 = (int(cy - half), int(cy + half))
    pad = np.full((y1 - y0, x1 - x0), 235, np.uint8)
    sx0, sy0 = (max(0, x0), max(0, y0))
    sx1, sy1 = (min(g.shape[1], x1), min(g.shape[0], y1))
    pad[sy0 - y0:sy1 - y0, sx0 - x0:sx1 - x0] = g[sy0:sy1, sx0:sx1]
    lo, hi = (np.percentile(pad, 1), np.percentile(pad, 99.5))
    pad = np.clip((pad.astype(float) - lo) / max(1, hi - lo) * 255, 0, 255).astype(np.uint8)
    ctx = cv2.cvtColor(cv2.resize(pad, (T, T), interpolation=cv2.INTER_CUBIC), cv2.COLOR_GRAY2RGB)
    s = T / (x1 - x0)
    bx0, by0 = (int((p['x'] - x0) * s) - 2, int((p['y'] - y0) * s) - 2)
    cv2.rectangle(ctx, (bx0, by0), (int(bx0 + p['w_px'] * s) + 3, int(by0 + p['h_px'] * s) + 3), (220, 0, 0), 1)
    mk = np.full((y1 - y0, x1 - x0), 255, np.uint8)
    mk[p['y'] - y0:p['y'] - y0 + p['h_px'], p['x'] - x0:p['x'] - x0 + p['w_px']][p['mask'] > 0] = 0
    mk = cv2.cvtColor(cv2.resize(mk, (T, T), interpolation=cv2.INTER_NEAREST), cv2.COLOR_GRAY2RGB)
    return (ctx, mk)

def write_sheets(ids, byid, imgs, outdir, prefix, cols, rps, T):
    per = cols * rps
    names = []
    for s0 in range(0, len(ids), per):
        chunk = ids[s0:s0 + per]
        sheet = np.full((rps * (T + 18), cols * (2 * T + 8), 3), 255, np.uint8)
        for k, pid in enumerate(chunk):
            r, c = divmod(k, cols)
            ctx, mk = tile_for(byid[pid], imgs, T)
            ox, oy = (c * (2 * T + 8), r * (T + 18))
            sheet[oy:oy + T, ox:ox + T] = ctx
            sheet[oy:oy + T, ox + T + 2:ox + 2 * T + 2] = mk
            cv2.putText(sheet, '%d' % (k + 1), (ox + 2, oy + T + 14), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
        nm = '%s_%02d.png' % (prefix, s0 // per + 1)
        cv2.imwrite(os.path.join(outdir, nm), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR))
        names.append(nm)
    return names

def cmd_sheets(a):
    P = load_pieces()
    byid = {p['pid']: p for p in P}
    imgs = {f: np.array(Image.open(SRC[f][0]).convert('L')) for f in SRC}
    ben = sorted((p['pid'] for p in P if p['kind'] != 'item9'))
    rng = np.random.default_rng(SEED)
    sd = ensure(os.path.join(OUT, 'sheets'))
    show = ben if len(ben) <= a.show_max else sorted(rng.choice(ben, size=a.show_max, replace=False).tolist())
    names = write_sheets(show, byid, imgs, sd, 'merged', a.cols, a.rows_per_sheet, a.tile)
    print('merged benched pieces %d; contact-sheet pieces %d on %d sheets' % (len(ben), len(show), len(names)))
    rng2 = np.random.default_rng(SEED + 72)
    lab = sorted(rng2.choice(ben, size=min(a.label_n, len(ben)), replace=False).tolist())
    order = rng2.permutation(len(lab))
    lab = [lab[k] for k in order]
    n2 = write_sheets(lab, byid, imgs, OUT, 'label72_sheet', a.cols, a.rows_per_sheet, a.tile)
    with open(os.path.join(OUT, 'label72_sample.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['seq', 'sheet', 'cell', 'pid', 'source', 'kind', 'n_parts'])
        per = a.cols * a.rows_per_sheet
        for k, pid in enumerate(lab):
            w.writerow([k + 1, k // per + 1, k % per + 1, pid, byid[pid]['source'], byid[pid]['kind'], byid[pid]['n_parts']])
    print('label sample %d on %d sheets' % (len(lab), len(n2)))
LABEL_CLASSES = ['BENCHED-GALLOWS', 'PLAIN-GALLOWS', 'NOT-GALLOWS', 'MERGE-ERROR']

def cmd_labels(a):
    samp = list(csv.DictReader(open(os.path.join(OUT, 'label72_sample.csv'))))
    lab = {}
    for ln in open(os.path.join(OUT, a.raw)):
        t = ln.split(None, 2)
        if len(t) < 2:
            continue
        assert t[1] in LABEL_CLASSES, ln
        lab[int(t[0])] = (t[1], t[2].strip() if len(t) > 2 else '')
    assert len(lab) == len(samp), (len(lab), len(samp))
    rows = [dict(r, hand=lab[int(r['seq'])][0], note=lab[int(r['seq'])][1]) for r in samp]
    with open(os.path.join(OUT, a.out), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        [w.writerow(r) for r in rows]
    from collections import Counter

    def prec(sub):
        c = Counter((r['hand'] for r in sub))
        n = len(sub)
        b = c['BENCHED-GALLOWS']
        return dict(n=n, counts=dict(c), precision_strict=b / n if n else None, precision_with_merge_error=(b + c['MERGE-ERROR']) / n if n else None)
    res = {'all': prec(rows)}
    for f_ in SRC:
        res[f_] = prec([r for r in rows if r['source'] == f_])
    for k in ('bench_merged', 'bench_single'):
        res[k] = prec([r for r in rows if r['kind'].startswith(k)])
    res['faint_bar_recovered'] = prec([r for r in rows if r['kind'].endswith('_enh')])
    res['main_mask'] = prec([r for r in rows if not r['kind'].endswith('_enh')])
    n = res['all']['n']
    b = res['all']['counts'].get('BENCHED-GALLOWS', 0)
    z = 1.96
    ph = b / n
    res['all']['wilson95'] = [(ph + z * z / (2 * n) - z * np.sqrt(ph * (1 - ph) / n + z * z / (4 * n * n))) / (1 + z * z / n), (ph + z * z / (2 * n) + z * np.sqrt(ph * (1 - ph) / n + z * z / (4 * n * n))) / (1 + z * z / n)]
    json.dump(res, open(os.path.join(OUT, a.out.replace('.csv', '.json')), 'w'), indent=1)
    print(json.dumps(res, indent=1))

def cmd_agree(a):
    """Reader 1 (label72_labels.csv) against the blind Codex second read (reader2/codex_out/sheet_NN.csv)."""
    from collections import Counter
    r1 = list(csv.DictReader(open(os.path.join(OUT, 'label72_labels.csv'))))
    r2 = {}
    for sh in sorted({int(r['sheet']) for r in r1}):
        for r in csv.DictReader(open(os.path.join(OUT, 'reader2', 'codex_out', 'sheet_%02d.csv' % sh))):
            assert r['class'] in LABEL_CLASSES, r
            r2[sh, int(r['cell'])] = (r['class'], r['confidence'])
    assert len(r2) == len(r1) == 72
    x = [r['hand'] for r in r1]
    y = [r2[int(r['sheet']), int(r['cell'])][0] for r in r1]
    n = len(x)
    po = sum((i == j for i, j in zip(x, y))) / n
    pe = sum((Counter(x)[c] * Counter(y)[c] for c in LABEL_CLASSES)) / n / n
    ka = (po - pe) / (1 - pe) if pe < 1 else float('nan')

    def bin_stats(cls_set):
        bx = [v in cls_set for v in x]
        by_ = [v in cls_set for v in y]
        both = sum((i and j for i, j in zip(bx, by_)))
        o1 = sum((i and (not j) for i, j in zip(bx, by_)))
        o2 = sum((j and (not i) for i, j in zip(bx, by_)))
        ne = n - both - o1 - o2
        return dict(both=both, reader1_only=o1, reader2_only=o2, neither=ne, positive_agreement=2 * both / (2 * both + o1 + o2) if both + o1 + o2 else None, both_over_either=both / (both + o1 + o2) if both + o1 + o2 else None, reader1_total=both + o1, reader2_total=both + o2)
    out = dict(n=n, raw_4class=po, kappa_4class=ka, confusion={'%s|%s' % k: v for k, v in sorted(Counter(zip(x, y)).items())}, benched=bin_stats({'BENCHED-GALLOWS'}), benched_or_merge_error=bin_stats({'BENCHED-GALLOWS', 'MERGE-ERROR'}), reader2_counts=dict(Counter(y)), reader1_counts=dict(Counter(x)))
    kinds = {}
    for k in ('bench_merged', 'bench_single'):
        idx = [i for i, r in enumerate(r1) if r['kind'].startswith(k)]
        bx = [x[i] == 'BENCHED-GALLOWS' for i in idx]
        by_ = [y[i] == 'BENCHED-GALLOWS' for i in idx]
        both = sum((i and j for i, j in zip(bx, by_)))
        o1 = sum((i and (not j) for i, j in zip(bx, by_)))
        o2 = sum((j and (not i) for i, j in zip(bx, by_)))
        kinds[k] = dict(n=len(idx), both=both, reader1_only=o1, reader2_only=o2, positive_agreement=2 * both / (2 * both + o1 + o2) if both + o1 + o2 else None, reader2_precision=sum(by_) / len(idx))
    out['by_kind'] = kinds
    out['reader2_precision_benched'] = sum((v == 'BENCHED-GALLOWS' for v in y)) / n
    rows = [dict(seq=r['seq'], pid=r['pid'], source=r['source'], kind=r['kind'], reader1=r['hand'], reader2=y[i], reader2_conf=r2[int(r['sheet']), int(r['cell'])][1], r1_note=r['note']) for i, r in enumerate(r1)]
    with open(os.path.join(OUT, 'reader2', 'label72_both_readers.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        [w.writerow(r) for r in rows]
    json.dump(out, open(os.path.join(OUT, 'reader2', 'agreement.json'), 'w'), indent=1)
    print(json.dumps(out, indent=1))

def cmd_inventory(a):
    """Merged benched gallows on every item 9 input folio, then the EVA bench reference over the whole page and over every folio
    that has a scan on disk (the item 9 inputs have boxes only for f1r, f49v, f88r and the f57v.3 ring crops)."""
    P = load_pieces()
    inv = {}
    for f in SRC:
        sub = [p for p in P if p['source'] == f]
        inv[f] = dict(pieces=len(sub), benched=sum((p['kind'] != 'item9' for p in sub)), merged=sum((p['kind'].startswith('bench_merged') for p in sub)), single=sum((p['kind'].startswith('bench_single') for p in sub)), faint_bar_recovered=sum((p['kind'].endswith('_enh') for p in sub)))
    inv['all_text_folios'] = {k: sum((inv[f][k] for f in SRC)) for k in ('pieces', 'benched', 'merged', 'single', 'faint_bar_recovered')}
    z = np.load(os.path.join(LANE, 'msi', 'runs', 'item5', 'ring3_crops.npz'))
    ms = []
    for k in z.files:
        m = (z[k] > 0).astype(np.uint8)
        ys, xs = np.nonzero(m)
        if len(ys) >= 30:
            ms.append(m[ys.min():ys.max() + 1, xs.min():xs.max() + 1])
    mh = float(np.median([m.shape[0] for m in ms]))
    rb = [bar_test(m, mh, PARAMS, single=True)[0] for m in ms]
    inv['f57v.3_ring'] = dict(pieces=len(ms), passing_single_piece_bar_test=int(sum(rb)), note='ring crops are single straightened pieces, no merging step is possible, not counted in the folio totals')

    def eva_bench_of(fol):
        tot = dict.fromkeys(('bench', 'units'), 0)
        for n, typ, txt in I.zl_lines(fol):
            c = I.eva_count(I.eva_clean(txt))
            tot['bench'] += c['bench']
            tot['units'] += c['units']
        return tot
    inv['eva_whole_page'] = {f: eva_bench_of(f) for f in SRC}
    tif = sorted(os.listdir(I.TIF))
    fol = set()
    for t in tif:
        mm = re.match('\\d+_(\\d+)([rv])(.*)\\.tif$', t)
        if not mm:
            continue
        n, rv, rest = (mm.group(1), mm.group(2), mm.group(3))
        fol.add('f%s%s' % (n, rv))
        for m2 in re.findall('_and_(\\d+)([rv])', rest):
            fol.add('f%s%s' % m2)
    allz = {}
    for ln in open(I.ZL, encoding='utf-8', errors='replace'):
        m = re.match('<(f[0-9]+[rv])([0-9]*)\\.(\\d+),(.)(\\w+)>\\s*(.*)$', ln.rstrip('\n'))
        if m:
            allz.setdefault(m.group(1), []).append(m.group(6))
    ev = {f: sum((I.eva_count(I.eva_clean(t))['bench'] for t in L)) for f, L in allz.items()}
    scanned = {f: v for f, v in ev.items() if f in fol}
    inv['eva_bench_all_zl_folios'] = dict(folios=len(ev), total=sum(ev.values()))
    inv['eva_bench_folios_with_scan_on_disk'] = dict(folios=len(scanned), total=sum(scanned.values()), scan_files=len(tif), top_folios=sorted(scanned.items(), key=lambda kv: -kv[1])[:12])
    json.dump(inv, open(os.path.join(OUT, 'inventory.json'), 'w'), indent=1)
    print(json.dumps(inv, indent=1))
