"""Retained item9_seed_crosstab.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__))
LANE = os.path.dirname(os.path.abspath(__file__))
ITEM9 = ''
OUT = ''
TIF = ''
ZL = ''
SRC = {}
SEED = 20261007
CLASSES = ['LOOP-SHAPE', 'GALLOWS-PLAIN', 'GALLOWS-BENCH', 'GALLOWS-LOOP', 'HOOK-TERMINAL', 'VESSEL-OPEN', 'VESSEL-CLOSED', 'DOWNSTROKE', 'CONNECTOR', 'LIGATURE', 'OTHER', 'FRAGMENT', 'MULTI']

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_seed_crosstab.py', 'cmd': cmd, 'argv': sys.argv[1:], 'args': args, 'seed': SEED, 'time': ts}, open(os.path.join(ensure(OUT), 'run_args_%s_%s.json' % (cmd, ts)), 'w'), indent=1)

def split_wide(m, med_h, wide):
    """Same as glyph_shape_inventory.split_wide, but also returns each part's (dx, dy) origin inside m."""
    h, w = m.shape
    if w <= wide * med_h:
        return [(m, 0, 0)]
    prof = m.sum(0).astype(float)
    prof = np.convolve(prof, np.ones(3) / 3, 'same')
    thr = 0.18 * prof.max()
    cuts = [0]
    minw = int(0.35 * med_h)
    for x in range(minw, w - minw):
        if prof[x] <= thr and prof[x] <= prof[max(0, x - 2):x + 3].min() and (x - cuts[-1] >= minw) and (w - x >= minw):
            cuts.append(x)
    cuts.append(w)
    out = []
    for i in range(len(cuts) - 1):
        s = m[:, cuts[i]:cuts[i + 1]]
        ys, xs = np.nonzero(s)
        if len(ys) >= 20:
            out.append((s[ys.min():ys.max() + 1, xs.min():xs.max() + 1], cuts[i] + xs.min(), ys.min()))
    return out or [(m, 0, 0)]

def segment(ink_k=0.45, wide=1.6, min_area_frac=0.05):
    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, 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
            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 = min_area_frac * med_h * med_h
        for x, y, w, h, ar, m, bi in raw:
            if ar < amin or h < 0.35 * med_h or h > 4.0 * med_h:
                continue
            xo = x
            for pm, dx, dy in split_wide(m, med_h, wide):
                if pm.sum() < amin:
                    continue
                pieces.append(dict(src=fol, box=bi, mask=pm, x_csv=xo, x=x + dx, y=y + dy, y_csv=y, w=pm.shape[1], h=pm.shape[0], med_h=med_h))
                xo += pm.shape[1]
    return pieces

def load_clusters():
    return list(csv.DictReader(open(os.path.join(ITEM9, 'clusters.csv'))))

def norm24(m):
    hh, ww = m.shape
    sz = max(hh, ww) + 4
    sq = np.zeros((sz, sz), np.float32)
    oy, ox = ((sz - hh) // 2, (sz - ww) // 2)
    sq[oy:oy + hh, ox:ox + ww] = m
    return cv2.GaussianBlur(cv2.resize(sq, (24, 24), interpolation=cv2.INTER_AREA), (0, 0), 1.0)

def aligned_pieces():
    """Segment, then attach item 9 piece ids by matching order against clusters.csv (text folios only)."""
    cl = load_clusters()
    n_ring = sum((1 for r in cl if r['source'] == 'f57v.3'))
    ps = segment()
    text = [r for r in cl if r['source'] != 'f57v.3']
    assert len(ps) == len(text), 'piece count differs from clusters.csv: %d vs %d' % (len(ps), len(text))
    for p, r in zip(ps, text):
        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)
        p['piece'] = int(r['piece'])
        p['cluster'] = int(r['cluster'])
        p['rule_class'] = r['rule_class']
        p['holes'] = int(r['holes'])
        p['h_norm'] = float(r['h_norm'])
        p['w_norm'] = float(r['w_norm'])
    return (ps, n_ring)

def bar_geom(m):
    """Longest horizontal run fraction (of piece width) in the 30 to 85 percent height band, and its row (fraction of h)."""
    h, w = m.shape
    best = (0.0, 0.0)
    for yy in range(int(0.3 * h), min(h, int(0.85 * h) + 1)):
        row = m[yy]
        run = mx = 0
        for v in row:
            run = run + 1 if v else 0
            mx = max(mx, run)
        if mx / w > best[0]:
            best = (mx / w, yy / h)
    return best

def cmd_sample(a):
    ps, n_ring = aligned_pieces()
    print('segmentation replica matches clusters.csv for %d text-folio pieces' % len(ps))
    out = ensure(OUT)
    with open(os.path.join(out, 'pieces_geom.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['piece', 'source', 'box', 'x', 'y', 'w_px', 'h_px', 'h_norm', 'w_norm', 'holes', 'rule_class', 'cluster', 'bar_frac', 'bar_row'])
        for p in ps:
            p['bar_frac'], p['bar_row'] = bar_geom(p['mask'])
            w.writerow([p['piece'], p['src'], p['box'], p['x'], p['y'], p['w'], p['h'], p['h_norm'], p['w_norm'], p['holes'], p['rule_class'], p['cluster'], round(p['bar_frac'], 3), round(p['bar_row'], 3)])
    rng = np.random.default_rng(SEED)
    by = {p['piece']: p for p in ps}

    def pick(ids, k):
        ids = sorted(ids)
        return sorted(rng.choice(ids, size=k, replace=False).tolist()) if len(ids) > k else ids
    c26 = pick([p['piece'] for p in ps if p['cluster'] == 26], 120)
    c31 = pick([p['piece'] for p in ps if p['cluster'] == 31], 120)
    taken = set(c26) | set(c31)
    rb = [p['piece'] for p in ps if p['rule_class'] == 'GALLOWS-BENCH' and p['piece'] not in taken]
    geo = [p['piece'] for p in ps if p['piece'] not in taken and p['piece'] not in rb and (p['h_norm'] >= 1.4) and (p['w_norm'] >= 0.8) and (p['bar_frac'] >= 0.6)]
    geo = pick(geo, 100)
    bench = sorted(rb + geo)
    taken |= set(bench)
    ctrl = pick([p['piece'] for p in ps if p['piece'] not in taken], a.control)
    rows = [(i, 'c26') for i in c26] + [(i, 'c31') for i in c31] + [(i, 'bench_rule') for i in rb] + [(i, 'bench_geom') for i in geo] + [(i, 'control') for i in ctrl]
    order = rng.permutation(len(rows))
    rows = [rows[k] for k in order]
    print('sample: c26 %d, c31 %d, bench_rule %d, bench_geom %d, control %d, total %d' % (len(c26), len(c31), len(rb), len(geo), len(ctrl), len(rows)))
    sd = ensure(os.path.join(out, 'sheets'))
    per = a.cols * a.rows_per_sheet
    imgs = {fol: np.array(Image.open(SRC[fol][0]).convert('L')) for fol in SRC}
    T = a.tile
    with open(os.path.join(out, 'seed_sample.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['seq', 'sheet', 'cell', 'piece', 'source', 'stratum', 'cluster', 'rule_class'])
        for s0 in range(0, len(rows), per):
            sh = s0 // per + 1
            chunk = rows[s0:s0 + per]
            sheet = np.full((a.rows_per_sheet * (T + 18), a.cols * (2 * T + 8), 3), 255, np.uint8)
            for k, (pid, stratum) in enumerate(chunk):
                p = by[pid]
                r, c = divmod(k, a.cols)
                seq = s0 + k + 1
                w.writerow([seq, sh, k + 1, pid, p['src'], stratum, p['cluster'], p['rule_class']])
                g = imgs[p['src']]
                mh = p['med_h']
                cx, cy = (p['x'] + p['w'] / 2, p['y'] + p['h'] / 2)
                half = max(p['w'], p['h']) / 2 + 0.75 * 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'] * s) + 3, int(by0 + p['h'] * 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'], p['x'] - x0:p['x'] - x0 + p['w']][p['mask'] > 0] = 0
                mk = cv2.cvtColor(cv2.resize(mk, (T, T), interpolation=cv2.INTER_NEAREST), cv2.COLOR_GRAY2RGB)
                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)
            cv2.imwrite(os.path.join(sd, 'sheet_%02d.png' % sh), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR))
    print('wrote', len(rows), 'sample rows and', (len(rows) + per - 1) // per, 'sheets to', sd)

def cmd_assemble(a):
    samp = list(csv.DictReader(open(os.path.join(OUT, 'seed_sample.csv'))))
    lab = {}
    for fn in sorted(os.listdir(os.path.join(OUT, 'labels_raw'))):
        sh = int(re.findall('\\d+', fn)[0])
        for ln in open(os.path.join(OUT, 'labels_raw', fn)):
            t = ln.split(None, 3)
            if len(t) < 3:
                continue
            assert t[1] in CLASSES and t[2] in ('high', 'low'), ln
            lab[sh, int(t[0])] = (t[1], t[2], t[3].strip() if len(t) > 3 else '')
    n = 0
    with open(os.path.join(OUT, 'seed_labels.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['piece', 'source', 'cluster', 'rule_class', 'hand_class', 'confidence', 'note', 'stratum', 'sheet', 'cell'])
        for r in sorted(samp, key=lambda r: int(r['piece'])):
            k = (int(r['sheet']), int(r['cell']))
            if k not in lab:
                continue
            hc, cf, note = lab[k]
            n += 1
            w.writerow([r['piece'], r['source'], r['cluster'], r['rule_class'], hc, cf, note, r['stratum'], r['sheet'], r['cell']])
    print('seed_labels.csv rows', n, 'of', len(samp), 'sampled')
BENCH = ('cth', 'ckh', 'cph', 'cfh')
EVA_COLS = ['d', 'bench', 'ch', 'sh', 'k', 't', 'p', 'f', 'o', 'a', 'y', 'q', 'e', 'i', 'n', 'l', 'r', 's', 'other']

def zl_lines(folio):
    """ZL text lines of one folio, in order: (locus, type, raw text). Folio match is exact on the locus prefix."""
    out = []
    for ln in open(ZL, encoding='utf-8', errors='replace'):
        m = re.match('<(f[0-9]+[rv][0-9]*|fRos)\\.(\\d+),(.)(\\w+)>\\s*(.*)$', ln.rstrip('\n'))
        if m and m.group(1) == folio:
            out.append((int(m.group(2)), m.group(4), m.group(5)))
    return out

def eva_clean(t, cut_at_gap=False):
    t = re.sub('<!.*?>', '', t)
    if cut_at_gap and '<->' in t:
        t = t.split('<->')[0]
    t = re.sub('<[^>]*>', '', t)
    t = re.sub('\\[([^:\\]]*):[^\\]]*\\]', '\\1', t)
    t = re.sub('@\\d+;', '#', t)
    t = t.replace('{', '').replace('}', '').replace("'", '').replace('<', '').replace('>', '')
    return re.sub('[.,\\s-]', '', t)

def eva_count(t):
    c = dict.fromkeys(EVA_COLS, 0)
    i = 0
    units = 0
    while i < len(t):
        if t[i:i + 3] in BENCH:
            c['bench'] += 1
            i += 3
        elif t[i:i + 2] in ('ch', 'sh'):
            c[t[i:i + 2]] += 1
            i += 2
        elif t[i] in c and t[i] not in ('bench', 'ch', 'sh'):
            c[t[i]] += 1
            i += 1
        else:
            c['other'] += 1
            i += 1
        units += 1
    c['units'] = units
    return c

def load_geom():
    g = list(csv.DictReader(open(os.path.join(OUT, 'pieces_geom.csv'))))
    for r in g:
        for k in ('piece', 'box', 'x', 'y', 'w_px', 'h_px', 'holes', 'cluster'):
            r[k] = int(r[k])
        for k in ('h_norm', 'w_norm'):
            r[k] = float(r[k])
        r['med_h'] = r['h_px'] / r['h_norm'] if r['h_norm'] else 24.0
    return g

def find_rows(P, spacing_guess, k_expected=None):
    """Deskew by maximising projection sharpness, then peaks of the weighted centre profile. Returns angle, row centres."""
    cx = np.array([p['x'] + p['w_px'] / 2 for p in P])
    cy = np.array([p['y'] + p['h_px'] / 2 for p in P])
    small = np.array([p['h_norm'] <= 1.3 for p in P])
    wt = np.array([min(p['w_px'], 2.5 * p['med_h']) for p in P])
    xm = np.median(cx)
    best = None
    for ang in np.arange(-3.0, 3.01, 0.1):
        yy = cy - np.tan(np.radians(ang)) * (cx - xm)
        hist = np.bincount(np.clip(((yy[small] - yy.min()) / 2).astype(int), 0, None), weights=wt[small])
        hist = np.convolve(hist, np.exp(-0.5 * (np.arange(-15, 16) / 3.0) ** 2), 'same')
        s = (hist ** 2).sum()
        if best is None or s > best[0]:
            best = (s, ang)
    ang = best[1]
    yy = cy - np.tan(np.radians(ang)) * (cx - xm)
    y0 = yy.min()
    hist = np.bincount(((yy[small] - y0) / 2).astype(int), weights=wt[small]).astype(float)
    sig = spacing_guess / 2 / 6.0
    hist = np.convolve(hist, np.exp(-0.5 * (np.arange(-30, 31) / sig) ** 2), 'same')
    md = int(0.55 * spacing_guess / 2)
    pk = []
    for i in range(1, len(hist) - 1):
        if hist[i] >= hist[max(0, i - md):i + md + 1].max() and hist[i] > 0.12 * hist.max():
            pk.append(i)
    return (ang, xm, [y0 + 2 * i + 1 for i in pk], hist)

def assign_rows(P, ang, xm, rows):
    rows = np.array(rows)
    for p in P:
        cx = p['x'] + p['w_px'] / 2
        off = np.tan(np.radians(ang)) * (cx - xm)
        if p['h_norm'] <= 1.3:
            refs = [p['y'] + p['h_px'] / 2 - off]
        else:
            refs = [p['y'] + 0.5 * p['med_h'] - off, p['y'] + p['h_px'] - 0.5 * p['med_h'] - off]
        best = min(((abs(rows - r).min(), int(np.argmin(abs(rows - r)))) for r in refs))
        p['row'] = best[1]
        p['row_dist'] = best[0]

def fit_rows(P, spacing, thr=0.1, max_ang=1.5):
    """Rows of one box as straight lines y = a + b (x - xm). The box skew is the angle in +-max_ang degrees that makes the
    centre profile of x-height pieces sharpest (the range is capped because a skew of one line spacing over the box width
    aligns line i with line i+1 and is also sharp). Rows are peaks of the deskewed, smoothed profile."""
    cx = np.array([p['x'] + p['w_px'] / 2 for p in P])
    cy = np.array([p['y'] + p['h_px'] / 2 for p in P])
    small = np.array([p['h_norm'] <= 1.3 for p in P])
    xm = float(np.median(cx))
    best = None
    for ang in np.arange(-max_ang, max_ang + 1e-06, 0.1):
        yy = cy[small] - np.tan(np.radians(ang)) * (cx[small] - xm)
        h = np.bincount(((yy - yy.min()) / 2).astype(int)).astype(float)
        h = np.convolve(h, np.exp(-0.5 * (np.arange(-12, 13) / 2.5) ** 2), 'same')
        sc = (h ** 2).sum()
        if best is None or sc > best[0]:
            best = (sc, float(ang))
    b = np.tan(np.radians(best[1]))
    yy = cy[small] - b * (cx[small] - xm)
    y0 = yy.min()
    wt = np.array([min(p['w_px'], 2.5 * p['med_h']) for p in P])[small]
    h = np.bincount(((yy - y0) / 2).astype(int), weights=wt).astype(float)
    h = np.convolve(h, np.exp(-0.5 * (np.arange(-40, 41) / (spacing / 12.0)) ** 2), 'same')
    md = int(0.55 * spacing / 2)
    pk = [i for i in range(1, len(h) - 1) if h[i] >= h[max(0, i - md):i + md + 1].max() and h[i] > thr * h.max()]
    return ([(y0 + 2 * i + 1 - b * xm, b) for i in pk], best[1])

def assign_lines(P, lines):
    for p in P:
        cx = p['x'] + p['w_px'] / 2
        yl = np.array([a + b * cx for a, b in lines])
        if p['h_norm'] <= 1.3:
            refs = [p['y'] + p['h_px'] / 2]
        else:
            refs = [p['y'] + 0.5 * p['med_h'], p['y'] + p['h_px'] - 0.5 * p['med_h']]
        best = min(((abs(yl - r).min(), int(np.argmin(abs(yl - r)))) for r in refs))
        p['row'] = best[1]
        p['row_dist'] = float(best[0])
SPACING = {'f1r': 85, 'f49v': 85, 'f88r': 68}
EXPECT_ROWS = {'f1r': [25], 'f49v': [13, 13], 'f88r': [5, 5, 6]}
XMAX = {'f1r': 2390}
ROWMAP = {'f1r': {}, 'f49v': {}, 'f88r': {}}
_f1r = [[1], [2], [3], [4], [5, 6], [7], [8], [9, 10]] + [[n] for n in range(11, 20)] + [[20, 21]] + [None] + [[n] for n in range(22, 27)] + [[27, 28]]
for r, z in enumerate(_f1r):
    ROWMAP['f1r'][0, r] = (z, False) if z else 'spurious row: the doodle bar above paragraph 4, no text line'
for r in range(13):
    ROWMAP['f49v'][0, r] = ([2 * r + 1, 2 * r + 2], False)
for r, why in ((0, 'about four glyphs past the box right edge'), (2, 'three glyphs past the box right edge'), (9, 'two glyphs past the box right edge'), (10, 'three glyphs past the box right edge'), (11, 'a word past the box right edge'), (12, 'line 26 straddles the box boundary and the right edge')):
    ROWMAP['f49v'][0, r] = why
ROWMAP['f49v'][1, 0] = 'lower halves of line 26, cut by the box boundary'
for k in range(1, 13):
    ROWMAP['f49v'][1, k] = ([25 + 2 * k, 26 + 2 * k], True)
ROWMAP['f88r'][0, 0] = 'line 7 is cut through the middle by the box top'
for k in range(1, 5):
    ROWMAP['f88r'][0, k] = ([7 + k], False)
for k in range(5):
    ROWMAP['f88r'][1, k] = ([18 + k], False)
for k in range(6):
    ROWMAP['f88r'][2, k] = ([26 + k], False)
ROWMAP['f88r'][2, 3] = 'line 29, one or two glyphs past the box right edge'
ROWMAP['f88r'][2, 4] = 'line 30, the last word past the box right edge'

def build_lines(g):
    """Rows per box, the row to ZL map, and per kept row the EVA counts. Returns (rows, piece_row, folio_status)."""
    rows, prow, status = ([], {}, {})
    for fol in ('f1r', 'f49v', 'f88r'):
        path, sc, boxes = SRC[fol]
        P = [p for p in g if p['source'] == fol]
        zl = {n: (typ, txt) for n, typ, txt in zl_lines(fol)}
        found = []
        for b in range(len(boxes)):
            Pb = [p for p in P if p['box'] == b]
            L, ang = fit_rows(Pb, SPACING[fol])
            assign_lines(Pb, L)
            found.append(len(L))
            sp = float(np.median(np.diff([a + bb * 1500 for a, bb in L]))) if len(L) > 1 else SPACING[fol]
            for p in Pb:
                cx = p['x'] + p['w_px'] / 2
                ok = p['row_dist'] <= 0.45 * sp and cx <= XMAX.get(fol, 1000000000.0)
                prow[p['piece']] = (fol, b, p['row'], ok)
            for r, (a, bb) in enumerate(L):
                ent = ROWMAP[fol].get((b, r), 'not in the row map')
                rec = dict(folio=fol, box=b, row=r, line_y=round(a + bb * 1500, 1), angle=ang, kept=isinstance(ent, tuple), n_pieces=sum((1 for p in Pb if p['row'] == r and prow[p['piece']][3])))
                if isinstance(ent, tuple):
                    zls, cut = ent
                    txt = []
                    for n in zls:
                        typ, raw = zl[n]
                        txt.append(eva_clean(raw, cut_at_gap=cut and typ.startswith('P')))
                    rec.update(zl_lines=' '.join(map(str, zls)), eva=''.join(txt), **eva_count(''.join(txt)))
                else:
                    rec.update(zl_lines='', eva='', drop_reason=ent)
                rows.append(rec)
        ok = found == EXPECT_ROWS[fol]
        status[fol] = dict(rows_found=found, rows_expected=EXPECT_ROWS[fol], aligned=ok, kept=sum((1 for r in rows if r['folio'] == fol and r['kept'])))
        if not ok:
            for r in rows:
                if r['folio'] == fol:
                    r['kept'] = False
                    r['drop_reason'] = 'folio dropped: row count differs from the ZL count'
    return (rows, prow, status)

def cmd_lines(a):
    g = load_geom()
    rows, prow, status = build_lines(g)
    cols = ['folio', 'box', 'row', 'line_y', 'kept', 'zl_lines', 'n_pieces', 'units'] + EVA_COLS + ['eva', 'drop_reason']
    with open(os.path.join(OUT, 'lines.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=cols, extrasaction='ignore')
        w.writeheader()
        [w.writerow(r) for r in rows]
    with open(os.path.join(OUT, 'piece_lines.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['piece', 'source', 'box', 'row', 'in_row'])
        for pid in sorted(prow):
            fol, b, r, ok = prow[pid]
            w.writerow([pid, fol, b, r, int(ok)])
    pal = [(220, 0, 0), (0, 0, 230), (0, 150, 0), (190, 0, 190), (0, 140, 190)]
    for fol in ('f1r', 'f49v', 'f88r'):
        im = np.array(Image.open(SRC[fol][0]).convert('RGB'))
        P = [p for p in g if p['source'] == fol]
        kept = {(r['box'], r['row']): r for r in rows if r['folio'] == fol}
        for p in P:
            _, b, r, ok = prow[p['piece']]
            rr = kept.get((b, r))
            c = pal[r % 5] if ok and rr and rr['kept'] else (150, 150, 150)
            cv2.rectangle(im, (p['x'], p['y']), (p['x'] + p['w_px'], p['y'] + p['h_px']), c, 3 if c != (150, 150, 150) else 2)
        x0 = min((p['x'] for p in P)) - 230
        x1 = max((p['x'] + p['w_px'] for p in P)) + 40
        y0 = min((p['y'] for p in P)) - 40
        y1 = max((p['y'] + p['h_px'] for p in P)) + 40
        for (b, r), rr in kept.items():
            lab = '%d.%d L%s' % (b, r, rr['zl_lines'].replace(' ', '+')) if rr['kept'] else '%d.%d drop' % (b, r)
            cv2.putText(im, lab, (max(0, x0 + 4), int(rr['line_y'] - np.tan(np.radians(rr['angle'])) * (1500 - x0 - 4)) + 10), cv2.FONT_HERSHEY_SIMPLEX, 1.1, pal[r % 5] if rr['kept'] else (120, 120, 120), 3)
        c = im[max(0, y0):y1, max(0, x0):x1]
        s = 1800 / max(c.shape[:2])
        Image.fromarray(cv2.resize(c, None, fx=s, fy=s, interpolation=cv2.INTER_AREA)).save(os.path.join(OUT, 'lines_%s.png' % fol))
    for fol, st in status.items():
        kr = [r for r in rows if r['folio'] == fol and r['kept']]
        rr = float(np.corrcoef([r['n_pieces'] for r in kr], [r['units'] for r in kr])[0, 1]) if len(kr) > 2 else float('nan')
        st['r_pieces_vs_eva_units'] = rr
        print(fol, json.dumps(st))
    json.dump(status, open(os.path.join(OUT, 'lines_status.json'), 'w'), indent=1)
SHAPE_MAIN = ['LOOP-SHAPE', 'GALLOWS-BENCH', 'GALLOWS-LOOP', 'GALLOWS-PLAIN', 'HOOK-TERMINAL', 'VESSEL-OPEN', 'VESSEL-CLOSED', 'LIGATURE', 'CONNECTOR', 'OTHER', 'MULTI', 'FRAGMENT']
EVA_X = EVA_COLS + ['gallows_all', 'g_ch', 'bench_or_g_ch', 'units']

def item9_dist(F, Hn, Wn, A, B):
    return 1 - F[A] @ F[B].T + 0.3 * np.abs(Hn[A][:, None] - Hn[B][None, :]) / 2 + 0.2 * np.abs(np.log(Wn[A][:, None] / Wn[B][None, :]))

def table(rows_lab, cols_lab, pairs):
    t = {r: dict.fromkeys(cols_lab, 0) for r in rows_lab}
    for r, c in pairs:
        t[r][c] += 1
    return t

def write_table(path, t, cols, first='rule_class'):
    with open(path, 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow([first] + cols + ['total'])
        for r, d in t.items():
            if sum(d.values()):
                w.writerow([r] + [d[c] for c in cols] + [sum(d.values())])

def within(x, grp):
    x = np.asarray(x, float).copy()
    for gname in set(grp):
        m = np.array([gg == gname for gg in grp])
        x[m] -= x[m].mean()
    return x

def resid(x, z, grp):
    """Residual of x on z with a separate intercept and slope per folio."""
    x = np.asarray(x, float).copy()
    out = np.zeros_like(x)
    for gname in set(grp):
        m = np.array([gg == gname for gg in grp])
        X = np.c_[np.ones(m.sum()), z[m]]
        beta = np.linalg.lstsq(X, x[m], rcond=None)[0]
        out[m] = x[m] - X @ beta
    return out

def corr_cols(A, B):
    A = A - A.mean(0)
    B = B - B.mean(0)
    na = np.sqrt((A ** 2).sum(0))
    nb = np.sqrt((B ** 2).sum(0))
    with np.errstate(invalid='ignore', divide='ignore'):
        return A.T @ B / np.outer(na, nb)

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)
    seeds = list(csv.DictReader(open(os.path.join(OUT, 'seed_labels.csv'))))
    by_piece = {int(r['piece']): r for r in seeds}
    hand_classes = [c for c in CLASSES if any((r['hand_class'] == c for r in seeds))]
    rule_classes = sorted(set((r['rule_class'] for r in seeds)))
    say('seed labels', len(seeds), json.dumps({c: sum((r['hand_class'] == c for r in seeds)) for c in hand_classes}))
    say('high-confidence', sum((r['confidence'] == 'high' for r in seeds)))
    res = {'n_seed': len(seeds), 'hand_counts': {c: sum((r['hand_class'] == c for r in seeds)) for c in hand_classes}, 'hand_counts_high': {c: sum((r['hand_class'] == c and r['confidence'] == 'high' for r in seeds)) for c in hand_classes}}
    t = table(rule_classes, hand_classes, [(r['rule_class'], r['hand_class']) for r in seeds])
    write_table(os.path.join(OUT, 'measure_confusion_rule_vs_hand.csv'), t, hand_classes)
    agree = sum((r['rule_class'] == r['hand_class'] for r in seeds))
    say('rule_class == hand_class: %d / %d = %.3f' % (agree, len(seeds), agree / len(seeds)))
    res['rule_agreement_all'] = agree / len(seeds)
    rule_prec = {}
    for rc in rule_classes:
        sub = [r for r in seeds if r['rule_class'] == rc]
        rule_prec[rc] = dict(n=len(sub), hand_same=sum((r['hand_class'] == rc for r in sub)), frac=sum((r['hand_class'] == rc for r in sub)) / len(sub))
    hand_rec = {}
    for hc in hand_classes:
        sub = [r for r in seeds if r['hand_class'] == hc]
        hand_rec[hc] = dict(n=len(sub), rule_same=sum((r['rule_class'] == hc for r in sub)), frac=sum((r['rule_class'] == hc for r in sub)) / len(sub))
    res['rule_precision'] = rule_prec
    res['rule_recall'] = hand_rec
    for rc in ('LOOP-SHAPE', 'GALLOWS-BENCH', 'GALLOWS-PLAIN', 'GALLOWS-LOOP'):
        if rc in rule_prec:
            say('rule %s: %d seeds, hand agrees %d (%.2f); hand %s seeds caught by rule %d of %d' % (rc, rule_prec[rc]['n'], rule_prec[rc]['hand_same'], rule_prec[rc]['frac'], rc, hand_rec.get(rc, {}).get('rule_same', 0), hand_rec.get(rc, {}).get('n', 0)))
    ctl = [r for r in seeds if r['stratum'] == 'control']
    agc = sum((r['rule_class'] == r['hand_class'] for r in ctl))
    say('control stratum: rule == hand %d / %d = %.3f' % (agc, len(ctl), agc / max(1, len(ctl))))
    res['rule_agreement_control'] = agc / max(1, len(ctl))
    pur = {}
    with open(os.path.join(OUT, 'measure_cluster_purity.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['cluster', 'n_labelled', 'hand_class', 'count', 'frac', 'high_conf'])
        for cl in (26, 31):
            sub = [r for r in seeds if int(r['cluster']) == cl]
            cnt = {c: sum((r['hand_class'] == c for r in sub)) for c in hand_classes}
            top = max(cnt, key=cnt.get)
            pur[cl] = dict(n=len(sub), top=top, purity=cnt[top] / len(sub), counts={k: v for k, v in cnt.items() if v})
            for c in sorted(cnt, key=lambda c: -cnt[c]):
                if cnt[c]:
                    w.writerow([cl, len(sub), c, cnt[c], round(cnt[c] / len(sub), 3), sum((r['hand_class'] == c and r['confidence'] == 'high' for r in sub))])
            say('cluster c%d: %d labelled, purity %.3f (%s), %s' % (cl, len(sub), pur[cl]['purity'], top, json.dumps(pur[cl]['counts'])))
    res['cluster_purity'] = pur
    ps, _ = aligned_pieces()
    idx = {p['piece']: k for k, p in enumerate(ps)}
    F = np.stack([norm24(p['mask']).ravel() for p in ps])
    F -= F.mean(1, keepdims=True)
    F /= np.linalg.norm(F, axis=1, keepdims=True) + 1e-09
    Hn = np.array([p['h_norm'] for p in ps])
    Wn = np.array([p['w_norm'] for p in ps])
    S = np.array([idx[int(r['piece'])] for r in seeds])
    lab = np.array([r['hand_class'] for r in seeds])
    Dss = item9_dist(F, Hn, Wn, S, S)
    np.fill_diagonal(Dss, np.inf)
    nn = Dss.argmin(1)
    pred = lab[nn]
    loo = float((pred == lab).mean())
    strata = np.array([r['stratum'] for r in seeds])
    say('1-NN leave-one-out accuracy on the seed set: %.3f (n=%d)' % (loo, len(seeds)))
    loo_s = {s_: float((pred[strata == s_] == lab[strata == s_]).mean()) for s_ in sorted(set(strata))}
    say('  by stratum', json.dumps({k: round(v, 3) for k, v in loo_s.items()}))
    pr = {}
    with open(os.path.join(OUT, 'measure_loo.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['hand_class', 'n', 'predicted', 'correct', 'recall', 'precision'])
        for c in hand_classes:
            n = int((lab == c).sum())
            npred = int((pred == c).sum())
            ok = int(((lab == c) & (pred == c)).sum())
            pr[c] = dict(n=n, predicted=npred, correct=ok, recall=ok / n if n else None, precision=ok / npred if npred else None)
            w.writerow([c, n, npred, ok, round(ok / n, 3) if n else '', round(ok / npred, 3) if npred else ''])
    for c in ('LOOP-SHAPE', 'GALLOWS-BENCH'):
        say('  LOO %s: recall %.3f precision %.3f' % (c, pr[c]['recall'], pr[c]['precision']))
    res.update(loo_accuracy=loo, loo_by_stratum=loo_s, loo_by_class=pr)
    nulls = [float((lab[nn] == lab).mean()) for lab in [rng.permutation(lab) for _ in range(1000)]]
    lab = np.array([r['hand_class'] for r in seeds])
    say('  LOO under label shuffle: mean %.3f, 99th pct %.3f' % (np.mean(nulls), np.percentile(nulls, 99)))
    res['loo_shuffle_mean'] = float(np.mean(nulls))
    sub = np.array([('LOOP-SHAPE/crossed' if r['note'].startswith('crossed') else 'LOOP-SHAPE/plain') if r['hand_class'] == 'LOOP-SHAPE' else r['hand_class'] for r in seeds])
    for c in ('LOOP-SHAPE/plain', 'LOOP-SHAPE/crossed'):
        n = int((sub == c).sum())
        ok = int(((sub == c) & (sub[nn] == c)).sum())
        npred = int((sub[nn] == c).sum())
        say('  LOO %s: n=%d recall %.3f precision %.3f' % (c, n, ok / n, ok / max(1, npred)))
        pr[c] = dict(n=n, predicted=npred, correct=ok, recall=ok / n, precision=ok / max(1, npred))
    allk = np.arange(len(ps))
    prop = np.empty(len(ps), dtype=object)
    prop_sub = np.empty(len(ps), dtype=object)
    dist = np.zeros(len(ps))
    for c0 in range(0, len(ps), 500):
        Dk = item9_dist(F, Hn, Wn, allk[c0:c0 + 500], S)
        j = Dk.argmin(1)
        prop[c0:c0 + 500] = lab[j]
        prop_sub[c0:c0 + 500] = sub[j]
        dist[c0:c0 + 500] = Dk[np.arange(len(j)), j]
    for k, s_ in enumerate(S):
        prop[s_] = lab[k]
        prop_sub[s_] = sub[k]
        dist[s_] = 0.0
    with open(os.path.join(OUT, 'measure_piece_labels.csv'), 'w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['piece', 'source', 'cluster', 'rule_class', 'label', 'label_sub', 'from_seed', 'nn_dist'])
        for k, p in enumerate(ps):
            w.writerow([p['piece'], p['src'], p['cluster'], p['rule_class'], prop[k], prop_sub[k], int(p['piece'] in by_piece), round(dist[k], 4)])
    pc = {c: int((prop == c).sum()) for c in hand_classes}
    say('propagated label counts (3 text folios)', json.dumps(pc))
    res['propagated_counts'] = pc
    g = load_geom()
    rows, prow, status = build_lines(g)
    kept = [r for r in rows if r['kept']]
    key = {(r['folio'], r['box'], r['row']): n for n, r in enumerate(kept)}
    shape_vars = ['hand:' + c for c in SHAPE_MAIN] + ['rule:' + c for c in ('LOOP-SHAPE', 'GALLOWS-BENCH', 'GALLOWS-PLAIN', 'GALLOWS-LOOP')] + ['sub:LOOP-SHAPE/plain', 'sub:LOOP-SHAPE/crossed', 'c26', 'c31', 'pieces']
    Xs = np.zeros((len(kept), len(shape_vars)))
    for k, p in enumerate(ps):
        fol, b, r, ok = prow[p['piece']]
        n = key.get((fol, b, r))
        if n is None or not ok:
            continue
        for j, v in enumerate(shape_vars):
            if v == 'hand:' + str(prop[k]) or v == 'sub:' + str(prop_sub[k]) or v == 'rule:' + p['rule_class'] or (v == 'c26' and p['cluster'] == 26) or (v == 'c31' and p['cluster'] == 31) or (v == 'pieces'):
                Xs[n, j] += 1
    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']
    Ye = np.array([[r[c] for c in 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 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()}))
    tot = dict(zip(shape_vars, Xs.sum(0).astype(int).tolist()))
    tote = dict(zip(EVA_X, Ye.sum(0).astype(int).tolist()))
    say('EVA on kept lines: bench %d, gallows before ch/sh %d, all gallows %d' % (tote['bench'], tote['g_ch'], tote['gallows_all']))
    say('totals on kept lines: hand LOOP-SHAPE %d (plain %d, crossed %d) vs EVA d %d, l %d; hand GALLOWS-BENCH %d vs EVA bench %d; pieces %d vs EVA units %d' % (tot['hand:LOOP-SHAPE'], tot['sub:LOOP-SHAPE/plain'], tot['sub:LOOP-SHAPE/crossed'], tote['d'], tote['l'], tot['hand:GALLOWS-BENCH'], tote['bench'], tot['pieces'], tote['units']))
    res['line_totals_shape'] = tot
    res['line_totals_eva'] = tote
    units = Ye[:, EVA_X.index('units')]
    Xc = np.stack([within(Xs[:, j], grp) for j in range(Xs.shape[1])], 1)
    Yc = np.stack([within(Ye[:, j], grp) for j in range(Ye.shape[1])], 1)
    Xr = np.stack([resid(Xs[:, j], units, grp) for j in range(Xs.shape[1])], 1)
    Yr = np.stack([resid(Ye[:, j], units, grp) for j in range(Ye.shape[1])], 1)
    R = corr_cols(Xc, Yc)
    Rp = corr_cols(Xr, Yr)
    folios = sorted(set(grp))
    gi = {f_: np.where(np.array(grp) == f_)[0] for f_ in folios}
    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(corr_cols(Xc[perm], Yc)) >= np.abs(R) - 1e-12
        gep += np.abs(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'] + 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 = 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 = ['ch', 'sh', 'k', 't', 'p', 'f', 'l', 'o', 'y']
    pred = {}
    for v, target in (('hand:LOOP-SHAPE', 'd'), ('hand:GALLOWS-BENCH', 'bench'), ('rule:LOOP-SHAPE', 'd'), ('rule:GALLOWS-BENCH', 'bench'), ('c26', 'd'), ('c26', 'l'), ('sub:LOOP-SHAPE/plain', 'd'), ('sub:LOOP-SHAPE/crossed', 'd'), ('sub:LOOP-SHAPE/crossed', 'l'), ('sub:LOOP-SHAPE/plain', 'l'), ('hand:LOOP-SHAPE', 'l'), ('c31', 'bench'), ('c31', 'gallows_all'), ('hand:GALLOWS-BENCH', 'gallows_all'), ('hand:GALLOWS-BENCH', 'g_ch'), ('hand:GALLOWS-BENCH', 'bench_or_g_ch'), ('c31', 'bench_or_g_ch')):
        d_ = cell(v, target)
        d_['controls'] = {c: cell(v, c) for c in [c for c in controls if c != target] + [x for x in ('d', 'bench') if x != target]}
        j = shape_vars.index(v)
        row_r = {c: float(Rp[j, EVA_X.index(c)]) for c in EVA_COLS}
        d_['rank_partial_among_eva_cols'] = 1 + sum((1 for c, x in row_r.items() if x > row_r.get(target, -9) and c != target)) if target in row_r else None
        pred['%s ~ %s' % (v, target)] = d_
        say('%-22s ~ %-11s 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 (('hand:LOOP-SHAPE', 'd'), ('sub:LOOP-SHAPE/plain', 'd'), ('sub:LOOP-SHAPE/crossed', 'l'), ('hand:GALLOWS-BENCH', 'bench'), ('hand:GALLOWS-BENCH', 'bench_or_g_ch')):
            x = Xs[m, shape_vars.index(v)]
            y = Ye[m, 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()))
    lofo = {}
    for v, target in (('hand:LOOP-SHAPE', 'd'), ('sub:LOOP-SHAPE/plain', 'd'), ('sub:LOOP-SHAPE/crossed', 'l'), ('hand:GALLOWS-BENCH', 'bench')):
        j = shape_vars.index(v)
        e = EVA_X.index(target)
        for f_ in folios:
            m = np.array([gg != f_ for gg in grp])
            gm = [gg for gg in grp if gg != f_]
            x = within(Xs[m, j], gm)
            y = 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['%s~%s without %s' % (v, target, f_)] = dict(n=int(m.sum()), r=r0, p=(c + 1) / 2001)
            say('  LOFO %s ~ %s without %s: n=%d r=%.3f p=%.4f' % (v, target, f_, m.sum(), r0, (c + 1) / 2001))
    res['leave_one_folio_out'] = lofo
    res['per_folio'] = pf
    res['lines_status'] = status
    res['perms'] = a.perms
    res['seed'] = SEED
    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')
