# radial-outside test for all labelled spots: march outward from the umbilicus through the spot (L2, same z) and
# report the distance to the first CT > 100 voxel beyond the spot (in a 5x5 tube), before leaving the mask/volume
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])
lab = {int(k): v for k, v in json.load(open('labels_user_1102.json')).items()}
pts = []
for r in csv.DictReader(open('spots.tsv'), delimiter='\t'):
    pts.append((int(r['id']), int(r['x_L0']) // 4, int(r['y_L0']) // 4, int(r['z_L0']) // 4))
for rnd in ('val2', 'val3'):
    lt = open(f'{rnd}/labels_user_1102_r{rnd[-1]}.txt').read().split(':')[1].split()
    lab.update({int(m[:-1]): m[-1] for m in lt})
    pts += [(t['id'], t['x'], t['y'], t['z']) for t in json.load(open(f'{rnd}/{rnd}_spots.json'))]
D = json.load(open('val3/val3_spots.json')); D2 = json.load(open('val2/val2_spots.json'))
dct = {t['id']: t['d_ct100'] for t in D + D2}
for r in csv.DictReader(open('dist_feats.tsv'), delimiter='\t'): dct[int(r['id'])] = float(r['d_ct100'])
out = []
for i, x, y, z in pts:
    cx, cy = np.interp(z, uz, ux), np.interp(z, uz, uy)
    d = np.array([x - cx, y - cy]); d /= np.linalg.norm(d); nrm = np.array([-d[1], d[0]])
    L = 1500
    zs = slice(z - 2, z + 3)
    # read a bounding box of the outward ray in chunks of 128 vx
    first = None; left = None
    for s0 in range(1, L, 128):
        ss = np.arange(s0, s0 + 128)
        px = x + d[0] * ss; py = y + d[1] * ss
        x0, x1 = int(min(px.min(), px.max())) - 3, int(max(px.min(), px.max())) + 4
        y0, y1 = int(min(py.min(), py.max())) - 3, int(max(py.min(), py.max())) + 4
        x0, y0 = max(x0, 0), max(y0, 0)
        a = np.asarray(ct[zs, y0:y1, x0:x1])
        if a.size == 0: break
        best = np.zeros(len(ss)); zero = np.ones(len(ss), bool)
        for o in (-2, -1, 0, 1, 2):
            qx = np.rint(px + nrm[0] * o).astype(int) - x0; qy = np.rint(py + nrm[1] * o).astype(int) - y0
            okk = (qx >= 0) & (qy >= 0) & (qx < a.shape[2]) & (qy < a.shape[1])
            v = np.zeros((a.shape[0], len(ss))); v[:, okk] = a[:, qy[okk], qx[okk]]
            best = np.maximum(best, v.max(0)); zero &= (v == 0).all(0)
        hit = np.nonzero(best > 100)[0]; zr = np.nonzero(zero)[0]
        h = hit[0] if len(hit) else 10 ** 9; zz = zr[0] if len(zr) else 10 ** 9
        if h < zz: first = s0 + h; break
        if zz < 10 ** 9: left = s0 + zz; break
    out.append(dict(id=i, lab=lab[i], d_ct100=dct.get(i), outward_papyrus=None if first is None else int(first), mask_exit=None if left is None else int(left)))
json.dump(out, open('radial_all.json', 'w'), indent=0)
print(len(out))
