#!/usr/bin/env python3
"""CU-001 data test of the recto/verso lighting split.
Maps are in leaf frame (versos mirrored, fore-edge right). For each leaf, fit a plane G = c + sx*x + sy*y
on clean parchment only (mask v2 NaNs already removed) in the centre band x .20-.80, y .20-.80.
Image-frame x slope: recto = sx, verso = -sx (un-mirror). A camera light fixed in the image gives the SAME
image-frame slope on both faces (what the split assumes: antisymmetric in leaf frame). Handling, and any
light that mirrors with the book, gives the same LEAF-frame slope (flips in image frame).
  L = (img_r + img_v)/2  fixed-in-image term;  H = (leaf_r + leaf_v)/2 mirror-symmetric term.
Prediction check: fixed term predicts the fore-band lighting difference (v - r)/2 = 0.4*L (fore band centre x .90 vs centre .50).
Second part: per-leaf plane correction (divide G by its fitted plane, normalised at centre) then recompute
fore_band and foot_mid indices for recto and verso, handling = mean, vs Plut. same treatment."""
import sys, json, glob, re
import numpy as np
from pathlib import Path
sys.path.insert(0, '../../../resources/tools/provenance/index.html#s-a2699091825cc62e')
import wear_lens as wl, wear_analyze as wa
OUT = Path('../../../resources/tools/provenance/index.html#s-4c61f2646b9fb2ef')
GH, GW = wl.GH, wl.GW
Z = {'fore_band': (.85, .95, .20, .80), 'foot_mid': (.40, .60, .87, .95)}
yy, xx = np.mgrid[0:GH, 0:GW]; X = (xx + .5) / GW; Y = (yy + .5) / GH
CEN = (X > .2) & (X < .8) & (Y > .2) & (Y < .8)

def fit(G):
    m = CEN & np.isfinite(G)
    if m.sum() < 4000: return None
    A = np.c_[np.ones(m.sum()), X[m] - .5, Y[m] - .5]; g = G[m]
    for _ in range(3):
        c = np.linalg.lstsq(A, g, rcond=None)[0]; r = g - A @ c
        k = np.abs(r) < 3 * 1.4826 * np.median(np.abs(r)) + 1e-9
        A, g = A[k], g[k]
    return c

def idx(G):
    o = {}
    for k, (a, b, c, d) in Z.items():
        v = G[int(c * GH):int(d * GH), int(a * GW):int(b * GW)]
        o[k] = 1 - float(np.nanmedian(v)) if np.isfinite(v).sum() > 50 else None
    return o

def load(pattern, layer):
    rows = []
    for f in sorted(glob.glob(pattern)):
        m = re.search(r'(\d+)([rv])\.npy$', f)
        if not m: continue
        G = np.load(f).astype(np.float32); G = G[0] if layer else G
        c = fit(G)
        if c is None: continue
        plane = c[0] + c[1] * (X - .5) + c[2] * (Y - .5)
        Gc = G / plane * c[0]            # remove tilt, keep level at centre
        i0, i1 = idx(G), idx(Gc)
        if None in i0.values() or None in i1.values(): continue
        rows.append({'side': m.group(2), 'sx': c[1] / c[0], 'sy': c[2] / c[0], 'raw': i0, 'corr': i1})
    return rows

def summ(rows, rnd):
    r = [x for x in rows if x['side'] == 'r']; v = [x for x in rows if x['side'] == 'v']
    out = {'n_r': len(r), 'n_v': len(v)}
    sr = [x['sx'] for x in r]; sv = [x['sx'] for x in v]
    out['leaf_frame_sx'] = {'r': wa.boot(sr, rnd), 'v': wa.boot(sv, rnd)}      # per leaf-width, + = brighter toward fore-edge
    img_r, img_v = sr, [-s for s in sv]
    out['image_frame_sx'] = {'r': wa.boot(img_r, rnd), 'v': wa.boot(img_v, rnd)}
    out['L_fixed_in_image'] = round((np.mean(img_r) + np.mean(img_v)) / 2, 4)
    out['H_mirror_symmetric'] = round((np.mean(sr) + np.mean(sv)) / 2, 4)
    sy_r, sy_v = [x['sy'] for x in r], [x['sy'] for x in v]
    out['sy'] = {'r': wa.boot(sy_r, rnd), 'v': wa.boot(sy_v, rnd)}
    Lb = [(np.mean(rnd.choice(img_r, len(img_r))) + np.mean(rnd.choice(img_v, len(img_v)))) / 2 for _ in range(2000)]
    out['L_ci'] = [round(float(np.percentile(Lb, 2.5)), 4), round(float(np.percentile(Lb, 97.5)), 4)]
    out['predicted_fore_lighting_(v-r)/2_=_0.4L'] = round(0.4 * out['L_fixed_in_image'], 4)
    for kind in ('raw', 'corr'):
        for k in Z:
            a = [x[kind][k] for x in r]; b = [x[kind][k] for x in v]
            # handling = mean of face means; bootstrap leaves within face, combine
            br = np.array([np.mean(rnd.choice(a, len(a))) for _ in range(2000)])
            bv = np.array([np.mean(rnd.choice(b, len(b))) for _ in range(2000)])
            h = (br + bv) / 2
            out[f'{kind}_{k}'] = {'r': wa.boot(a, rnd), 'v': wa.boot(b, rnd),
                                  'handling': [round(float((np.mean(a) + np.mean(b)) / 2), 4), round(float(np.percentile(h, 2.5)), 4), round(float(np.percentile(h, 97.5)), 4)],
                                  'lighting_(v-r)/2': round((np.mean(b) - np.mean(a)) / 2, 4)}
    return out

rnd = np.random.default_rng(20261008)
vms_rows = load(str(OUT / 'maps' / '*.npy'), True)
ctrl = {'plut': load(str(OUT / 'maps_plut' / '*.npy'), False)}
if (OUT / 'maps_sl').exists() and '--two' not in sys.argv:
    ctrl['sloane'] = load(str(OUT / 'maps_sl' / '*.npy'), False)
    ctrl['pooled'] = ctrl['plut'] + ctrl['sloane']          # two controls, leaves pooled
if '--four' in sys.argv:        # flag: add BL Egerton 2020 and an all-controls pool; default (three-control) output unchanged
    ctrl['egerton'] = load(str(OUT / 'maps_eg' / '*.npy'), False)
    ctrl['pooled_all'] = ctrl['plut'] + ctrl['sloane'] + ctrl['egerton']
res = {'vms': summ(vms_rows, rnd)}
for k, rows in ctrl.items(): res[k] = summ(rows, rnd)

def hb(rows, kind, k):
    a = np.array([x[kind][k] for x in rows if x['side'] == 'r']); b = np.array([x[kind][k] for x in rows if x['side'] == 'v'])
    return a, b
def hmean(a, b): return (rnd.choice(a, len(a)).mean() + rnd.choice(b, len(b)).mean()) / 2
for cname, crows in ctrl.items():
    for kind in ('raw', 'corr'):
        for k in Z:
            va, vb = hb(vms_rows, kind, k); pa, pb = hb(crows, kind, k)
            rat, dif = [], []
            for _ in range(4000):
                hv, hp = hmean(va, vb), hmean(pa, pb)
                dif.append(hv - hp); rat.append(hv / hp if hp > 0.003 else np.nan)
            hv0 = (va.mean() + vb.mean()) / 2; hp0 = (pa.mean() + pb.mean()) / 2
            rr = np.array(rat)
            res[f'ratio_{cname}_{kind}_{k}'] = {'ms408': round(float(hv0), 4), 'control': round(float(hp0), 4),
                'ratio': round(float(hv0 / hp0), 2) if hp0 > 0.003 else None,
                'diff_ci': [round(float(np.percentile(dif, 2.5)), 4), round(float(np.percentile(dif, 97.5)), 4)],
                'ratio_ci_valid_draws': [round(float(np.nanpercentile(rr, 2.5)), 2), round(float(np.nanpercentile(rr, 97.5)), 2), int(np.isfinite(rr).sum())] if np.isfinite(rr).sum() > 100 else None,
                'recto_only_ms408_minus_control': round(float(va.mean() - pa.mean()), 4)}
(OUT / ('lighting_gradient_four.json' if '--four' in sys.argv else 'lighting_gradient_two.json' if '--two' in sys.argv else 'lighting_gradient_three.json')).write_text(json.dumps(res, indent=1, default=float))
print(json.dumps({k: v for k, v in res.items() if k in ('sloane', 'egerton') or k.startswith('ratio_')}, indent=1, default=float))
