"""Day 4 mechanistic test: test M1 (in-sample/direction noise), M2 (LayerNorm norm coupling), and M3 (competitor-hurdle co-movement)
on the cached gelu-1l 2^22 shards for hex, camel, english.
Usage: python3 run_day4_mech.py DIST THREADS
Frozen plan: PLAN.md (tracker #71 / #77). Written by Gemini 4 Carbon (High), 2026-11-23.
"""
import json, math, os, sys, time
import numpy as np
import torch as th


def spearman_rho(x: np.ndarray, y: np.ndarray) -> float:
    """Pure-NumPy Spearman rank correlation (average ranks on ties, no scipy dependency)."""
    def avg_ranks(a):
        order = np.argsort(a, kind="mergesort")
        s = a[order]
        n = len(s)
        r = np.empty(n, dtype=np.float64)
        # Find run boundaries for ties
        diff = np.concatenate(([True], s[1:] != s[:-1], [True]))
        idx = np.flatnonzero(diff)
        for i in range(len(idx) - 1):
            lo, hi = idx[i], idx[i + 1]
            r[order[lo:hi]] = 0.5 * (lo + hi - 1)
        return r
    rx = avg_ranks(x)
    ry = avg_ranks(y)
    rx -= rx.mean()
    ry -= ry.mean()
    den = math.sqrt(float((rx * rx).sum()) * float((ry * ry).sum()))
    return float((rx * ry).sum() / den) if den > 0 else 0.0

OLD = os.environ.get("OLD", "/old")
WORK = os.environ.get("WORK", "/work")
sys.path.insert(0, f"{OLD}/code")
os.environ["JOB"] = OLD

import arcenv
from qld_multi import sav_direction
from qld_fast import bounds, count_chunk, interval_tables

dist, nth = sys.argv[1], int(sys.argv[2])
th.set_num_threads(nth)
T0 = time.time()
log = lambda *a: print(time.strftime("%H:%M:%S"), f"[day4:{dist}]", *a, flush=True)

OUT = f"{WORK}/out/{dist}"
os.makedirs(OUT, exist_ok=True)

# 1. Load pinned model weights (W_U, ln_final), Day 2-3 qld.json, tokens.json, and dirs.pt[2^20]
sd = th.load(f"{OLD}/model/model_final.pth", map_location="cpu", weights_only=True)
W_U = sd["unembed.W_U"].float()
w_ln = sd["ln_final.w"].double().numpy()
b_ln = sd["ln_final.b"].double().numpy()

qj = json.load(open(f"{OLD}/out/{dist}/qld.json"))
tok = json.load(open(f"{OLD}/out/tokens.json"))[dist]
targets = qj["targets"]
p_true = [float(v) for v in qj["p"]]
K = len(targets)
V = W_U.shape[1]

dp = th.load(f"{OLD}/out/{dist}/dirs.pt", map_location="cpu", weights_only=False)
N20 = 2**20
SH = 2**18
mean20, A20 = dp["white"][N20]
D20 = th.nan_to_num(dp["dirs"][N20])
ok20 = [not bool(th.isnan(dp["dirs"][N20][:, k]).any()) for k in range(K)]

shards = [np.load(f"{OLD}/acts/{dist}/{s:02d}.npy", mmap_mode="r") for s in range(16)]

def get_rows(s, e):
    out = [shards[i][max(s, i * SH) - i * SH: min(e, (i + 1) * SH) - i * SH]
           for i in range(s // SH, (e - 1) // SH + 1)]
    return th.from_numpy(np.ascontiguousarray(np.concatenate(out) if len(out) > 1 else out[0]))

# 2. Gate LN: check exact LayerNorm sphere equation on first 2048 rows of shard 00
x_ln_chk = np.asarray(shards[0][:2048], dtype=np.float64)
z_ln_chk = (x_ln_chk - b_ln) / w_ln
r2_dev = float(np.max(np.abs(np.sum(z_ln_chk**2, axis=1) - 512.0)))
sum_dev = float(np.max(np.abs(np.sum(z_ln_chk, axis=1))))
gate_ln_pass = (r2_dev <= 0.05) and (sum_dev <= 1e-3)
log(f"Gate LN: pass={gate_ln_pass} max_r2_dev={r2_dev:.3e} max_sum_dev={sum_dev:.3e}")
if not gate_ln_pass:
    raise RuntimeError(f"Gate LN failed on {dist}: r2_dev={r2_dev}, sum_dev={sum_dev}")

# Helper: compute exact QLD, Norm-Stratified QLD (16 bins), and hurdle coupling stats on a 2^20 slice [row_start, row_end)
inv_AT = th.inverse(A20.T)

def eval_slice(row_start, row_end, D_mat, ok_flags, compute_coupling=False, n_bins=16):
    n = row_end - row_start
    w_mat = inv_AT @ D_mat                          # (512, K)
    G_mat = (W_U.T @ A20) @ D_mat                   # (V, K)
    tabs = interval_tables(G_mat, targets)

    # Pass A: compute a_all (n, K) and whitened squared norm ||u_i||^2 (n,)
    a_chunks = []
    u2_chunks = []
    for s in range(row_start, row_end, 2**16):
        xc = get_rows(s, min(s + 2**16, row_end)) - mean20
        u_c = xc @ inv_AT                           # (m, 512) whitened u = (x - mean) @ inv(A.T)
        u2_chunks.append((u_c * u_c).sum(dim=1).numpy())
        a_chunks.append((xc @ w_mat).numpy())       # exact same float32 parenthesization as day23 run_qld.py:72
    a_all = np.concatenate(a_chunks, axis=0)        # (n, K) float32
    u2_all = np.concatenate(u2_chunks, axis=0)      # (n,) float32
    a_sorted = np.ascontiguousarray(np.sort(a_all, axis=0).T)  # (K, n)

    # Pre-sort a within 16 equal-count bins of ||b_i||_2 per token k
    # Note ||b_{i,k}||^2 = max(0, ||u_i||^2 - a_{i,k}^2)
    b_norm_bins = np.empty((n, K), dtype=np.int16)
    a_bin_sorted = [[None] * n_bins for _ in range(K)]
    bin_size = n // n_bins
    assert n % n_bins == 0
    for k in range(K):
        bn2 = np.maximum(0.0, u2_all - a_all[:, k] * a_all[:, k])
        order = np.argsort(bn2, kind="mergesort")
        bins_k = np.empty(n, dtype=np.int16)
        for q in range(n_bins):
            idx_q = order[q * bin_size:(q + 1) * bin_size]
            bins_k[idx_q] = q
            a_bin_sorted[k][q] = np.sort(a_all[idx_q, k])
        b_norm_bins[:, k] = bins_k

    # Pass B: sweep chunks of 1024 rows to compute lo, hi, Standard QLD counts, NS-QLD counts, and coupling summaries
    counts_std = np.zeros(K, dtype=np.int64)
    counts_ns = np.zeros(K, dtype=np.int64)

    # Subsample 65,536 evenly spaced rows (stride 16) for exact Spearman rho(a, lower(b)) & full 1,048,576 for tail hurdle shift!
    lower_all = np.empty((n, K), dtype=np.float32) if compute_coupling else None
    open_mask_counts = np.zeros(K, dtype=np.int64)
    joint_hits = np.zeros(K, dtype=np.int64)

    CH = 1024
    for s in range(0, n, CH):
        x = get_rows(row_start + s, row_start + s + CH)
        Lu = (x @ W_U).numpy()
        lo, hi = bounds(Lu, targets, tabs)          # lower = a + lo, upper = a + hi
        ac = a_all[s:s + CH]
        counts_std += count_chunk(ac, lo, hi, a_sorted)

        lower_c = ac + lo
        upper_c = ac + hi
        open_c = lower_c < upper_c
        open_mask_counts += open_c.sum(axis=0)
        joint_hits += ((ac > lower_c) & (ac < upper_c)).sum(axis=0)

        # Norm-stratified count within each bin q
        bc = b_norm_bins[s:s + CH]
        for k in range(K):
            lk = lower_c[:, k]
            uk = upper_c[:, k]
            bk = bc[:, k]
            tot_k = 0
            for q in range(n_bins):
                m_q = (bk == q)
                if m_q.any():
                    arr_q = a_bin_sorted[k][q]
                    cq = np.searchsorted(arr_q, uk[m_q], "left") - np.searchsorted(arr_q, lk[m_q], "left")
                    tot_k += int(np.clip(cq, 0, None).sum())
            counts_ns[k] += tot_k

        if compute_coupling:
            lower_all[s:s + CH] = lower_c

    est_std = [float(counts_std[k]) / (n * n) if ok_flags[k] else 0.0 for k in range(K)]
    # In NS-QLD: each of n_bins bins has bin_size = n / n_bins rows and searches an array of size bin_size,
    # so under uniformity total pair count denominator is n_bins * (bin_size^2) = n^2 / n_bins!
    denom_ns = float(n_bins) * float(bin_size) * float(bin_size)
    est_ns = [float(counts_ns[k]) / denom_ns if ok_flags[k] else 0.0 for k in range(K)]

    coupling = None
    if compute_coupling:
        coupling = []
        for k in range(K):
            ak = a_all[:, k]
            lk = lower_all[:, k]
            # Finite lower bounds (exclude -BIG if any, though rare tokens always have g_j < g_t)
            fin = np.isfinite(lk) & (lk > -1e30)
            ak_f = ak[fin]
            lk_f = lk[fin]
            # Spearman on 65,536 strided rows for speed & determinism
            rho = spearman_rho(ak_f[::16], lk_f[::16])
            q999_a = float(np.quantile(ak_f, 0.999))
            med_l_all = float(np.median(lk_f))
            med_l_hi_a = float(np.median(lk_f[ak_f >= q999_a]))
            delta_hurdle = (med_l_hi_a - med_l_all) / float(np.std(ak_f) + 1e-12)

            # Also check conditional a shift when lower(b) is favorable (< q999_a)
            fav = lk_f < q999_a
            mean_a_all = float(np.mean(ak_f))
            mean_a_fav = float(np.mean(ak_f[fav])) if int(fav.sum()) >= 10 else float("nan")
            sd_a_fav = float(np.std(ak_f[fav])) if int(fav.sum()) >= 10 else float("nan")
            coupling.append({
                "token": int(targets[k]),
                "spearman_a_lower": float(rho),
                "q999_a": q999_a,
                "med_lower_all": med_l_all,
                "med_lower_top01pct_a": med_l_hi_a,
                "delta_hurdle_sd": float(delta_hurdle),
                "n_favorable_b": int(fav.sum()),
                "mean_a_given_favorable_b": mean_a_fav,
                "sd_a_given_favorable_b": sd_a_fav,
                "open_gate_frac": float(open_mask_counts[k]) / n,
                "joint_hits_2p20": int(joint_hits[k]),
            })

    return est_std, est_ns, coupling

# 3. Run S0 (shards 00..03, in-sample 2^20) + Gate G0 verification!
log("Evaluating S0 (shards 00..03, n=2^20) + NS-QLD + hurdle coupling...")
est_S0, est_NS_S0, coupling_S0 = eval_slice(0, N20, D20, ok20, compute_coupling=True)
ref_est20 = [float(x) for x in qj["est"][str(N20)]]
rel_diffs = [abs(a - b) / max(abs(b), 1e-30) if b > 0 else abs(a - b) for a, b in zip(est_S0, ref_est20)]
max_g0_diff = max(rel_diffs)
log(f"Gate G0: max_rel_diff={max_g0_diff:.3e}")
if max_g0_diff > 1e-5:
    raise RuntimeError(f"Gate G0 failed on {dist}: max_rel_diff={max_g0_diff}")

# 4. Run held-out S1 (shards 04..07, n=2^20) and held-out S2 (shards 08..11, n=2^20) with fixed (mean20, A20, D20)
log("Evaluating held-out S1 (shards 04..07, n=2^20)...")
est_S1, est_NS_S1, _ = eval_slice(N20, 2 * N20, D20, ok20, compute_coupling=False)
log("Evaluating held-out S2 (shards 08..11, n=2^20)...")
est_S2, _, _ = eval_slice(2 * N20, 3 * N20, D20, ok20, compute_coupling=False)

# 5. Run 5 fresh direction-search seeds + 1 deterministic mean-logit-diff direction on S0 (n=2^20)
P20 = W_U.T @ A20
beta20 = W_U.T @ mean20
seed_ests = {}
seed_fails = {}
for m in range(1, 6):
    cols, ok_m, nf = [], [], 0
    for k, t in enumerate(targets):
        d = None
        for tr in range(3):
            try:
                d = sav_direction(P20, beta20, t, t + m * 10000 + tr * 10**6)
                break
            except Exception:
                nf += 1
        ok_m.append(d is not None)
        cols.append(d if d is not None else th.full((512,), 0.0))
    Dm = th.stack(cols, dim=1)
    em, _, _ = eval_slice(0, N20, Dm, ok_m, compute_coupling=False)
    seed_ests[f"seed_{m}"] = em
    seed_fails[f"seed_{m}"] = nf
    log(f"Direction seed {m}/5 done ({time.time()-T0:.0f}s)")

# Deterministic mean-logit-diff direction: d_det = normalize(P[t] - mean_j P[j])
P_mean = P20.mean(dim=0)
cols_det = []
for t in targets:
    v = P20[t] - P_mean
    cols_det.append(v / th.norm(v))
D_det = th.stack(cols_det, dim=1)
est_det, _, _ = eval_slice(0, N20, D_det, [True] * K, compute_coupling=False)
log(f"Deterministic direction done ({time.time()-T0:.0f}s)")

# 6. Direct empirical argmax count across all 16 shards (2^22) from Day 2-3's saved argmax_counts.pt
am22 = th.load(f"{OLD}/out/{dist}/argmax_counts.pt", map_location="cpu", weights_only=True).numpy()
emp_p_2p22 = [float(am22[t]) / float(2**22) for t in targets]

out_obj = {
    "dist": dist,
    "targets": targets,
    "p_true": p_true,
    "emp_p_2p22": emp_p_2p22,
    "gate_ln": {"pass": gate_ln_pass, "max_r2_dev": r2_dev, "max_sum_dev": sum_dev},
    "gate_g0": {"pass": True, "max_rel_diff": max_g0_diff},
    "est_day23_2p20": ref_est20,
    "est_day23_2p22": [float(x) for x in qj["est"][str(2**22)]],
    "est_S0_std": est_S0,
    "est_S0_ns16": est_NS_S0,
    "est_S1_std": est_S1,
    "est_S1_ns16": est_NS_S1,
    "est_S2_std": est_S2,
    "est_dir_seeds": seed_ests,
    "dir_seed_retries": seed_fails,
    "est_dir_deterministic": est_det,
    "coupling_S0": coupling_S0,
    "wall_sec": time.time() - T0,
}

tmp = f"{OUT}/day4_mech.json.tmp"
with open(tmp, "w") as f:
    json.dump(out_obj, f, indent=1)
os.replace(tmp, f"{OUT}/day4_mech.json")
log(f"DAY 4 DONE in {time.time()-T0:.1f}s")
