"""Scroll-extent envelope test (user 2026-11-02: papyrus label = 'the spiral should still treat this as part of the
scroll'; air = outside the scroll). PRE-REGISTERED before scoring: for each spot, cast radial rays from the umbilicus
on a neighbourhood grid (arc and z half-size N L2 vx, step 8 vx); r_out per ray = outermost radius with CT > 100
within [r_s - 150, r_s + 250]; envelope r_env = 90th percentile of r_out over the neighbourhood; OUTSIDE = r_s > r_env.
Primary N = 64; N = 0 (local ray only), 32 and 128 reported as sensitivity. Gate: OUTSIDE precision >= 98% (air).
"""
import numpy as np, zarr, json, csv
ct = zarr.open('/media/djosey/nvme4/20251211183505-2.399um-0.2m-78keV-masked.zarr', mode='r')['2']
U = json.load(open('/media/djosey/nvme4/spiral_0332/dataset/umbilicus.json'))['control_points']
uz = np.array([p['z'] for p in U]); ux = np.array([p['x'] for p in U]); uy = np.array([p['y'] for p in U])
R = json.load(open('radial_all.json')); pos = {}
for r in csv.DictReader(open('spots.tsv'), delimiter='\t'): pos[int(r['id'])] = tuple(int(r[k]) // 4 for k in ('x_L0', 'y_L0', 'z_L0'))
for rnd in ('val2', 'val3'):
    for t in json.load(open(f'{rnd}/{rnd}_spots.json')): pos[t['id']] = (t['x'], t['y'], t['z'])
NMAX, ST = 128, 8; rr = np.arange(-150, 251)
res = []
for t in R:
    x, y, z = pos[t['id']]
    dzs = np.arange(-NMAX, NMAX + 1, ST); arcs = np.arange(-NMAX, NMAX + 1, ST)
    rout = np.full((len(dzs), len(arcs)), np.nan)
    for a, dz in enumerate(dzs):
        zz = z + dz
        if zz < 0 or zz >= ct.shape[0]: continue
        cx, cy = np.interp(zz, uz, ux), np.interp(zz, uz, uy)
        c0x, c0y = np.interp(z, uz, ux), np.interp(z, uz, uy)
        rs = np.hypot(x - c0x, y - c0y); th0 = np.arctan2(y - c0y, x - c0x)
        th = th0 + arcs / rs
        R2 = rs + rr
        PX = cx + np.cos(th)[:, None] * R2[None]; PY = cy + np.sin(th)[:, None] * R2[None]
        x0, x1 = max(int(PX.min()) - 1, 0), min(int(PX.max()) + 2, ct.shape[2]); y0, y1 = max(int(PY.min()) - 1, 0), min(int(PY.max()) + 2, ct.shape[1])
        sl = np.asarray(ct[zz, y0:y1, x0:x1])
        qx = np.clip(np.rint(PX).astype(int) - x0, 0, sl.shape[1] - 1); qy = np.clip(np.rint(PY).astype(int) - y0, 0, sl.shape[0] - 1)
        v = sl[qy, qx] > 100
        for b in range(len(arcs)):
            h = np.nonzero(v[b])[0]
            if len(h): rout[a, b] = R2[h[-1]] - rs   # outermost papyrus radius relative to the spot radius
    t2 = dict(id=t['id'], lab=t['lab'])
    for N in (0, 32, 64, 128):
        m = (np.abs(dzs) <= N)[:, None] & (np.abs(arcs) <= N)[None]
        vals = rout[m]; vals = vals[np.isfinite(vals)]
        t2[f'env{N}'] = float(np.percentile(vals, 90)) if len(vals) else -999.   # spot is OUTSIDE if env < 0
    res.append(t2)
json.dump(res, open('envelope_all.json', 'w'), indent=0)
for N in (0, 32, 64, 128):
    o = [t for t in res if t[f'env{N}'] < 0]; a = sum(t['lab'] == 'A' for t in o)
    print(f'N {N:3d}: OUTSIDE {len(o)}, air {a}, precision {a / max(len(o), 1):.3f}; air recall {a}/{sum(t["lab"] == "A" for t in res)}')
