"""Branch-correct fiber jump map: where do network fibers leave their winding in a fit?

Replaces fiber_jump_map.py's comparison of the continuous winding W with the fitter's branch label q (off by up to
a whole winding depending on angle). Uses the stage-1 anchor records ({source_fiber, src_index, p (L2 xyz), w_cont})
and s1_score.anchor_rule: t = round(w_cont - phi/2pi), dev = q - t; a point is off when |dev| >= 0.5 or its phase
residual is rejected (|rho| > 0.4). Runs of >= MIN_RUN consecutive evaluated points (by src_index) with the same
nonzero k = round(dev) become segments.

    CUDA_VISIBLE_DEVICES= python fiber_jump_map_sheet.py RUN_DIR OUT_PREFIX [--records F ...] [--min-run 3]
Outputs OUT_PREFIX_points.npz, OUT_PREFIX_segments.tsv (L0 coordinates), OUT_PREFIX_fibers.tsv (per fiber).
"""
import argparse, collections, json, os, sys
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import numpy as np, torch
WORK = '/media/djosey/nvme4/spiral_0332/work'
sys.path.insert(0, f'{WORK}/s1'); sys.path.insert(0, WORK)
import s1_score as SC   # sets up the spiral-fitting import path
import slice_eval as S, flatten_spiral_checkpoint as fsc, sample_spiral

ap = argparse.ArgumentParser()
ap.add_argument('run'); ap.add_argument('out_prefix')
ap.add_argument('--records', nargs='+', default=[f'{WORK}/s1/anchors_train_records.json', f'{WORK}/s1/anchors_held_records.json'])
ap.add_argument('--min-run', type=int, default=3); ap.add_argument('--scale', type=float, default=4.0)
a = ap.parse_args()
recs, held = [], set()
for path in a.records:
    rs = json.load(open(path)); recs += rs
    if 'held' in os.path.basename(path): held |= {r['source_fiber'] for r in rs}
ck = S.load_checkpoint_cpu(f'{a.run.rstrip("/")}/checkpoint_fitted.ckpt')
m = fsc._build_model(ck, fsc._checkpoint_config(ck), fsc.Path(f'{S.D}/dataset/umbilicus.json'), torch.device('cpu'))
tfn, dr = m.get_slice_to_spiral_transform(), m.get_dr_per_winding().detach()
P = np.array([r['p'] for r in recs], np.float64)
inz = (P[:, 2] >= ck['z_begin']) & (P[:, 2] < ck['z_end'])
zyx = torch.tensor(P[inz][:, ::-1].copy(), dtype=torch.float32)
with torch.inference_mode():
    sp = torch.cat([tfn(zyx[i:i + 20000]) for i in range(0, len(zyx), 20000)])
    phi, _, shifted = sample_spiral.get_theta_and_radii(sp[:, 1:], dr)
q = (shifted / dr).numpy(); phi = phi.numpy()
w = np.array([r['w_cont'] for r in recs], np.float64)[inz]
t, rho, acc, off, nonf, rej = SC.anchor_rule(phi, q, w)
dev = q.astype(np.float64) - t
k = np.where(acc, np.round(dev), 0).astype(int)
names = np.array([r['source_fiber'][:-5] for r in recs])[inz]; idx = np.array([r['src_index'] for r in recs])[inz]
P = P[inz] * a.scale
segs, fibers = [], []
for f in sorted(set(names)):
    sel = np.flatnonzero(names == f); sel = sel[np.argsort(idx[sel])]
    kk = k[sel]; fibers.append(dict(fiber=f, held=int(f + '.json' in held), points=len(sel), off=int(off[sel].sum()),
                                    off_rate=round(float(off[sel].mean()), 3), rejected=int(rej[sel].sum()),
                                    z0=round(P[sel, 2].min()), z1=round(P[sel, 2].max()),
                                    k_hist=dict(collections.Counter(kk[kk != 0].tolist()))))
    i = 0
    while i < len(kk):
        j = i
        while j + 1 < len(kk) and kk[j + 1] == kk[i]: j += 1
        if kk[i] != 0 and j - i + 1 >= a.min_run:
            s = sel[i:j + 1]; mid = s[len(s) // 2]
            segs.append(dict(fiber=f, held=int(f + '.json' in held), k=int(kk[i]), npts=len(s),
                             len_L0=round(float(np.linalg.norm(np.diff(P[s], axis=0), axis=1).sum())),
                             frac_of_fiber=round(len(s) / len(sel), 3), z0=round(P[s, 2].min()), z1=round(P[s, 2].max()),
                             x=round(P[mid, 0]), y=round(P[mid, 1]), z=round(P[mid, 2]),
                             med_dev=round(float(np.median(dev[s])), 2), src0=int(idx[s[0]]), src1=int(idx[s[-1]])))
        i = j + 1
segs.sort(key=lambda s: -s['len_L0']); fibers.sort(key=lambda f: -f['off_rate'])
for path, rows in ((a.out_prefix + '_segments.tsv', segs), (a.out_prefix + '_fibers.tsv', fibers)):
    with open(path, 'w') as fh:
        keys = list(rows[0]) if rows else ['fiber']
        fh.write('\t'.join(keys) + '\n')
        for r in rows: fh.write('\t'.join(str(r[x]) for x in keys) + '\n')
np.savez_compressed(a.out_prefix + '_points.npz', fiber=names, src_index=idx, P_L0=P, q=q, t=t, rho=rho, dev=dev, k=k,
                    off=off, rejected=rej)
print(f'{len(fibers)} fibers, {len(names)} points evaluated, off {off.mean():.1%} (rejected {rej.mean():.1%}); '
      f'fibers with any off point {sum(f["off"] > 0 for f in fibers)}; {len(segs)} segments >= {a.min_run} pts, '
      f'k histogram {dict(collections.Counter(s["k"] for s in segs))}')
