# do the user's air/papyrus labels match inside/outside the outer shell? shell radius at each spot's (z, theta)
import numpy as np, tifffile, json, csv
D = '/media/djosey/nvme4/spiral_0332/dataset/outer_shell'
X, Y, Z = (tifffile.imread(f'{D}/{c}.tif').astype(float) for c in 'xyz')
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])
ok = (X > 0) | (Y > 0) | (Z > 0)
sx, sy, sz = X[ok], Y[ok], Z[ok]
print('shell pts', ok.sum(), 'x range', sx.min(), sx.max(), 'z range', sz.min(), sz.max())
scale = 4.0 if sx.max() > 5000 else 1.0     # shell in L0 or L2?
sx, sy, sz = sx / scale, sy / scale, sz / scale
cx, cy = np.interp(sz, uz, ux), np.interp(sz, uz, uy)
sr = np.hypot(sx - cx, sy - cy); sth = np.arctan2(sy - cy, sx - cx)
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'])
E = {t['id']: t for t in json.load(open('envelope_all.json'))}
out = []
for i, (x, y, z) in pos.items():
    c0x, c0y = np.interp(z, uz, ux), np.interp(z, uz, uy)
    rs = np.hypot(x - c0x, y - c0y); th = np.arctan2(y - c0y, x - c0x)
    dth = np.angle(np.exp(1j * (sth - th))) * rs
    m = (np.abs(sz - z) < 40) & (np.abs(dth) < 40)
    if not m.any(): continue
    out.append(dict(id=i, lab=E[i]['lab'], d_shell=float(np.median(sr[m]) - rs)))   # > 0: spot inside the shell
json.dump(out, open('shell_test.json', 'w'), indent=0)
P = sorted(t['d_shell'] for t in out if t['lab'] == 'P'); A = sorted(t['d_shell'] for t in out if t['lab'] == 'A')
q = lambda v: np.percentile(v, [0, 10, 50, 90, 100]).round(1)
print('n', len(out), 'P d_shell pct', q(P)); print('A d_shell pct', q(A))
for T in (-20, -10, 0, 10, 20, 30):
    o = [t for t in out if t['d_shell'] < T]; a = sum(t['lab'] == 'A' for t in o)
    print(f'OUTSIDE = d_shell < {T}: {len(o)} calls, air {a}, precision {a / max(len(o), 1):.3f}')
