#!/usr/bin/env python3
"""Deterministic verification of linear-stack collapse vs. ReLU manifold folding.

Generates public/research/why-llms-need-creases/out/results.json with exact metrics on:
1. Symmetric 4-point cross: (+2, 0), (-2, 0) -> class 0; (0, +2), (0, -2) -> class 1.
   - Proves any L-layer linear stack W_L(...(W_1 x + b_1)...) collapses to one affine map
     W_eff x + b_eff (max discrepancy < 1e-6), stalling at CE loss = ln(2) = 0.693147 and 50.0% accuracy.
   - Proves H=2 ReLU hinges (ReLU(+x_0) + ReLU(-x_0) = |x_0|) fold (-2, 0) onto (+2, 0),
     reaching 100.0% accuracy and CE loss < 0.005.
2. Concentric 2D rings (N=240 deterministic points, inner r=1.0 vs outer r=2.4):
   - Compare 3-layer deep linear (2 -> 16 -> 16 -> 2) vs 1-hidden-layer ReLU across widths
     H in {1, 2, 3, 4, 6, 8}, tracking accuracy, cross-entropy loss, and active linear regions.
"""

from __future__ import annotations

import hashlib
import json
import math
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F


def make_symmetric_cross() -> tuple[torch.Tensor, torch.Tensor]:
    X = torch.tensor(
        [[2.0, 0.0], [-2.0, 0.0], [0.0, 2.0], [0.0, -2.0]], dtype=torch.float64
    )
    y = torch.tensor([0, 0, 1, 1], dtype=torch.long)
    return X, y


def make_concentric_rings(n_per_ring: int = 120, seed: int = 7) -> tuple[torch.Tensor, torch.Tensor]:
    rng = np.random.default_rng(seed)
    angles_in = np.linspace(0.0, 2.0 * np.pi, n_per_ring, endpoint=False)
    angles_out = np.linspace(0.0, 2.0 * np.pi, n_per_ring, endpoint=False) + (np.pi / n_per_ring)
    r_in = 1.0 + rng.normal(0.0, 0.08, size=n_per_ring)
    r_out = 2.4 + rng.normal(0.0, 0.08, size=n_per_ring)
    inner = np.stack([r_in * np.cos(angles_in), r_in * np.sin(angles_in)], axis=1)
    outer = np.stack([r_out * np.cos(angles_out), r_out * np.sin(angles_out)], axis=1)
    X = torch.tensor(np.vstack([inner, outer]), dtype=torch.float64)
    y = torch.tensor([0] * n_per_ring + [1] * n_per_ring, dtype=torch.long)
    return X, y


def count_activation_regions(layer: nn.Linear, grid_res: int = 201, bound: float = 3.0) -> int:
    xs = torch.linspace(-bound, bound, grid_res, dtype=torch.float64)
    gx, gy = torch.meshgrid(xs, xs, indexing="xy")
    pts = torch.stack([gx.reshape(-1), gy.reshape(-1)], dim=1)
    with torch.no_grad():
        pre = pts @ layer.weight.T + layer.bias
        signs = (pre > 0).to(torch.int8).numpy()
    unique = np.unique(signs, axis=0)
    return int(len(unique))


def train_model(
    model: nn.Module, X: torch.Tensor, y: torch.Tensor, steps: int = 600, lr: float = 0.15
) -> dict[str, float]:
    model.double()
    opt = torch.optim.SGD(model.parameters(), lr=lr)
    for _ in range(steps):
        opt.zero_grad()
        logits = model(X)
        loss = F.cross_entropy(logits, y)
        loss.backward()
        opt.step()
    with torch.no_grad():
        logits = model(X)
        final_loss = float(F.cross_entropy(logits, y).item())
        preds = logits.argmax(dim=1)
        acc = float((preds == y).to(torch.float64).mean().item())
    return {"final_ce_loss": round(final_loss, 6), "accuracy": round(acc, 6)}


def verify_linear_collapse(X: torch.Tensor, y: torch.Tensor) -> dict:
    torch.manual_seed(0)
    deep_linear = nn.Sequential(
        nn.Linear(2, 16),
        nn.Linear(16, 16),
        nn.Linear(16, 2),
    ).double()
    stats = train_model(deep_linear, X, y, steps=600, lr=0.05)

    with torch.no_grad():
        L0, L1, L2 = deep_linear[0], deep_linear[1], deep_linear[2]
        # Collapse L2(L1(L0(x))) = W_eff x + b_eff
        W_eff = L2.weight @ L1.weight @ L0.weight
        b_eff = L2.weight @ (L1.weight @ L0.bias + L1.bias) + L2.bias
        collapsed_logits = X @ W_eff.T + b_eff
        deep_logits = deep_linear(X)
        max_diff = float(torch.max(torch.abs(deep_logits - collapsed_logits)).item())

    return {
        **stats,
        "collapsed_single_matrix_shape": list(W_eff.shape),
        "max_abs_logit_diff_vs_single_linear": max_diff,
    }


def main() -> None:
    out_dir = Path(__file__).resolve().parents[1] / "out"
    out_dir.mkdir(parents=True, exist_ok=True)

    X_cross, y_cross = make_symmetric_cross()
    cross_linear = verify_linear_collapse(X_cross, y_cross)

    cross_width_seed_rates = {}
    for w in (2, 4, 8):
        runs = []
        for s in range(20):
            torch.manual_seed(s)
            mw = nn.Sequential(nn.Linear(2, w), nn.ReLU(), nn.Linear(w, 2))
            runs.append({"seed": s, **train_model(mw, X_cross, y_cross, steps=600, lr=0.2)})
        solved = sum(1 for r in runs if r["accuracy"] == 1.0)
        cross_width_seed_rates[f"H={w}"] = {
            "hidden_units": w,
            "n_seeds": 20,
            "n_solved_100pct": solved,
            "solve_rate": round(solved / 20.0, 4),
            "median_ce_loss": round(float(np.median([r["final_ce_loss"] for r in runs])), 6),
            "min_ce_loss": round(min(r["final_ce_loss"] for r in runs), 6),
        }

    # Explicit analytic 2-hinge module verification
    analytic_m2 = nn.Sequential(nn.Linear(2, 2), nn.ReLU(), nn.Linear(2, 2)).double()
    with torch.no_grad():
        analytic_m2[0].weight.copy_(torch.tensor([[1.0, 0.0], [-1.0, 0.0]], dtype=torch.float64))
        analytic_m2[0].bias.zero_()
        analytic_m2[2].weight.copy_(torch.tensor([[5.0, 5.0], [-5.0, -5.0]], dtype=torch.float64))
        analytic_m2[2].bias.copy_(torch.tensor([-5.0, 5.0], dtype=torch.float64))
        a_logits = analytic_m2(X_cross)
        analytic_2hinge = {
            "final_ce_loss": round(float(F.cross_entropy(a_logits, y_cross).item()), 6),
            "accuracy": float((a_logits.argmax(dim=1) == y_cross).to(torch.float64).mean().item()),
        }

    # Analytic 2-hinge V-fold check: h = [ReLU(+x0), ReLU(-x0)] -> |x0| = h0 + h1
    with torch.no_grad():
        h_vfold = torch.stack([F.relu(X_cross[:, 0]), F.relu(-X_cross[:, 0])], dim=1)
        abs_x0 = h_vfold.sum(dim=1).tolist()

    X_rings, y_rings = make_concentric_rings()
    rings_linear = verify_linear_collapse(X_rings, y_rings)

    ring_sweep = []
    for width in [1, 2, 3, 4, 6, 8]:
        best = None
        # Deterministic multi-seed check (3 fixed seeds) so random dead-ReLU init doesn't distort small H
        for seed in (0, 1, 2):
            torch.manual_seed(seed)
            m = nn.Sequential(nn.Linear(2, width), nn.ReLU(), nn.Linear(width, 2))
            res = train_model(m, X_rings, y_rings, steps=900, lr=0.15)
            regions = count_activation_regions(m[0])
            cand = {"hidden_units": width, "seed": seed, **res, "active_2d_regions": regions}
            if best is None or cand["final_ce_loss"] < best["final_ce_loss"]:
                best = cand
        ring_sweep.append(best)

    payload = {
        "ln_2_theoretical_chance_ce": round(math.log(2.0), 6),
        "symmetric_cross_4pts": {
            "deep_linear_3layer_2_16_16_2": cross_linear,
            "analytic_2_hinges_exact": analytic_2hinge,
            "sgd_20seed_width_sweep": cross_width_seed_rates,
            "analytic_vfold_abs_x0": abs_x0,
        },
        "concentric_rings_240pts": {
            "deep_linear_3layer_2_16_16_2": rings_linear,
            "relu_width_sweep": ring_sweep,
        },
    }

    out_file = out_dir / "results.json"
    encoded = json.dumps(payload, indent=2) + "\n"
    out_file.write_text(encoded)
    sha = hashlib.sha256(encoded.encode("utf-8")).hexdigest()
    (out_dir / "manifest.json").write_text(
        json.dumps({"results_sha256": sha, "script": "code/verify_manifold_folding.py"}, indent=2) + "\n"
    )
    print(encoded)


if __name__ == "__main__":
    main()
