"""Day 1 main test: does Algorithm-3 QLD error fall as 1/sqrt(n) up to 2^20 when a and b are exactly independent?
Pass rules are fixed in ../PLAN.md (Day 1) before this script was first run. Tracker #71.
Written by Claude Opus 5.5 (Claude Code), 2026-11-17.

Toy: x ~ N(mu, Sigma) in d_model=16, vocabulary 64, logits x @ W_U. In the population-whitened space u ~ N(0, I),
so for any fixed unit d, a = u.d and b = u - a d are exactly independent and QLD's limit is the true probability.

Truth: Rao-Blackwellised along d* (ARC's shortest accepting vector computed with the true mean and covariance):
  p_t = E_b[ P(a in (lo(b), hi(b))) ],  a ~ N(0,1) exactly,  b sampled (float64, M samples, SE reported).

Estimators, each on R independent activation samples at each n:
  alg3   : variant b, sample whitening, ARC's SAV direction (the paper's Algorithm 3)   <- the pass rule
  y      : variant y (line 103 as published), sample whitening
  oracle : variant b with the true whitening and d*  (exact independence inside the estimator too)
Usage: toy_scaling.py DTYPE(float32|float64) [R] [LOG2N_MAX]
"""
import json
import math
import os
import sys
import time
from multiprocessing import get_context

import torch as th

from qld_multi import qld_multi, sav_direction, whiten

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "out")
DT = {"float32": th.float32, "float64": th.float64}[sys.argv[1]]
R = int(sys.argv[2]) if len(sys.argv) > 2 else 16
NMAX = int(sys.argv[3]) if len(sys.argv) > 3 else 20
DM, V, GEOM_SEED = 16, 64, 20261117
P_LO, P_HI, N_TARGETS = 1e-8, 1e-3, 12
M_SCREEN, M_TRUTH = 2**20, 2**26


def geometry(scale):
    g = th.Generator().manual_seed(GEOM_SEED)
    W_U = th.randn(DM, V, generator=g, dtype=th.float64)
    L = th.randn(DM, DM, generator=g, dtype=th.float64) / math.sqrt(DM)
    Sigma = L @ L.T + 0.5 * th.eye(DM, dtype=th.float64)
    C = th.linalg.cholesky(Sigma)
    mu = scale * th.randn(DM, generator=g, dtype=th.float64)
    return W_U, mu, C


def interval_prob(lo, hi):
    """P(lo < a < hi) for a ~ N(0,1), accurate in both tails."""
    nd = th.special.ndtr
    upper_tail = lo > 0
    p = th.where(upper_tail, nd(-lo) - nd(-hi), nd(hi) - nd(lo))
    return p.clamp(min=0)


def rb_truth(W_U, mu, C, t, d, M, chunk=2**18, seed=0):
    """Rao-Blackwellised P(argmax = t) along fixed unit d with exact N(0, I) whitened samples. Returns (p, se)."""
    P = W_U.T @ C
    beta = W_U.T @ mu
    g = P @ d
    den = -(g[t] - g)
    gen = th.Generator().manual_seed(seed)
    s1 = s2 = 0.0
    done = 0
    while done < M:
        m = min(chunk, M - done)
        z = th.randn(m, DM, generator=gen, dtype=th.float64)
        b = z - (z @ d)[:, None] * d[None, :]
        Lb = b @ P.T + beta
        num = Lb[:, t:t + 1] - Lb
        ratio = num / den
        lo = th.where(den < 0, ratio, -th.inf).max(-1).values
        hi = th.where(den > 0, ratio, th.inf).min(-1).values
        q = interval_prob(lo, hi)
        s1 += q.sum().item()
        s2 += (q * q).sum().item()
        done += m
    p = s1 / M
    var = max(s2 / M - p * p, 0.0)
    return p, math.sqrt(var / M)


def one_run(job):
    n_log2, rep, targets, W_U64, mu64, C64, Dstar64 = job
    th.set_num_threads(1)
    W_U, mu, C = W_U64.to(DT), mu64.to(DT), C64.to(DT)
    gen = th.Generator().manual_seed(1_000_003 * rep + n_log2)
    acts = (mu + th.randn(2**n_log2, DM, generator=gen, dtype=th.float64).to(DT) @ C.T)
    t0 = time.time()
    # ARC's direction search on the sample-whitened problem, per target; a failure is recorded, not hidden
    mean, A = whiten(acts)
    P, beta = W_U.T @ A, W_U.T @ mean
    cols, failed = [], []
    for k, t in enumerate(targets):
        try:
            cols.append(sav_direction(P, beta, t, seed=10_000 * rep + t))
        except (AssertionError, RuntimeError):
            cols.append(Dstar64[:, k].to(DT)); failed.append(k)
    D = th.stack(cols, dim=1)
    alg3, _ = qld_multi(W_U, acts, targets, variant="b", mean=mean, A=A, D=D)
    y, _ = qld_multi(W_U, acts, targets, variant="y", mean=mean, A=A, D=D)  # same directions as alg3
    oracle, _ = qld_multi(W_U, acts, targets, variant="b", mean=mu, A=C, D=Dstar64.to(DT))
    for k in failed:
        alg3[k] = y[k] = None
    return {"log2n": n_log2, "rep": rep, "alg3": alg3, "y": y, "oracle": oracle, "sav_failed": failed,
            "sec": time.time() - t0}


def main():
    os.makedirs(OUT, exist_ok=True)
    th.set_num_threads(8)
    # 1. Geometry: first mean scale with at least N_TARGETS tokens in [P_LO, P_HI] by a screening truth (float64).
    for scale in (1.0, 1.5, 2.0, 3.0, 4.0):
        W_U, mu, C = geometry(scale)
        P, beta = W_U.T @ C, W_U.T @ mu
        top = int(beta.argmax())  # ARC's direction search crashes on the token on top at the mean; not a rare target
        dstar = {}
        for t in range(V):
            if t == top:
                continue
            try:
                dstar[t] = sav_direction(P, beta, t, seed=t)
            except (AssertionError, RuntimeError):
                pass  # ARC's search found no point where t is on top: t never wins (p = 0), not a target
        screen = {t: rb_truth(W_U, mu, C, t, dstar[t], M_SCREEN, seed=1)[0] for t in dstar}
        inband = sorted([t for t in dstar if P_LO <= screen[t] <= P_HI], key=lambda t: screen[t])
        print(f"scale {scale}: {len(inband)} tokens in band", flush=True)
        if len(inband) >= N_TARGETS:
            break
    assert len(inband) >= N_TARGETS, "no scale gives enough targets"
    pick = [inband[round(i * (len(inband) - 1) / (N_TARGETS - 1))] for i in range(N_TARGETS)]  # spread over log p
    # 2. Truth for the picked targets.
    truth = {}
    for t in pick:
        p, se = rb_truth(W_U, mu, C, t, dstar[t], M_TRUTH, seed=2)
        truth[t] = (p, se)
        print(f"truth t={t} p={p:.4e} rel_se={se / p:.2e}", flush=True)
    Dstar = th.stack([dstar[t] for t in pick], dim=1)
    # 3. Scaling runs.
    jobs = [(k, r, pick, W_U, mu, C, Dstar) for k in range(10, NMAX + 1) for r in range(R)]
    jobs.sort(key=lambda j: -j[0])  # biggest first for load balance
    rows = []
    with get_context("spawn").Pool(8) as pool:
        for i, row in enumerate(pool.imap_unordered(one_run, jobs)):
            rows.append(row)
            if i % 16 == 0:
                print(f"{i + 1}/{len(jobs)} done (2^{row['log2n']} rep {row['rep']} {row['sec']:.1f}s)", flush=True)
    out = {"dtype": sys.argv[1], "R": R, "d_model": DM, "V": V, "scale": scale, "geom_seed": GEOM_SEED,
           "M_truth": M_TRUTH, "targets": pick, "truth": {str(t): truth[t] for t in pick},
           "screen": {str(t): screen[t] for t in screen}, "rows": rows}
    path = os.path.join(OUT, f"toy_{sys.argv[1]}.json")
    json.dump(out, open(path, "w"))
    print("wrote", path, flush=True)


if __name__ == "__main__":
    main()
