#!/usr/bin/env python3
"""
verify_P034.py -- Paper 34: Kleisli monad over S^3.

This verifier checks the frozen-constant arithmetic and audits the monad-law
claims for the paper's stated bind-as-centroid-collapse operation. The layer
fractions and threshold arithmetic mostly reproduce; the monad laws do not hold
for general scored distributions under the displayed collapse semantics.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from verify_common import CheckResult, Verifier


class ModernVerifier(Verifier):
    """Local adapter: tolerance logic inherited byte-identical from
    verify_common.Verifier; only the output layer is modernised."""

    def __init__(self, name: str) -> None:
        self.name = name
        self.results = []
        print(name)

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        n = len(self.results)
        desc = f"{label} -- {detail}" if detail else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        return ok

    def summary(self):
        passed = sum(r.ok for r in self.results)
        failed = len(self.results) - passed
        print(f"\n{'='*60}\nRESULT: {passed} PASS / {failed} FAIL")
        return 1 if failed else 0


v = ModernVerifier("P034 -- Kleisli Monad over S3")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "34_Paper_KleisliMonadS3.tex").read_text()
WORKSPACE = ROOT.parent

PI = math.pi
OMEGA = 4.0 * PI**3 + PI**2 + PI
FRAC_EDGE = PI / OMEGA
FRAC_BOUNDARY = PI**2 / OMEGA
FRAC_BULK = 4.0 * PI**3 / OMEGA
BREATH_PERIOD = PI * OMEGA
PLATEAU_THRESHOLD = 0.02


def dot(a: tuple[float, ...], b: tuple[float, ...]) -> float:
    return sum(x * y for x, y in zip(a, b))


def norm(q: tuple[float, ...]) -> float:
    return math.sqrt(dot(q, q))


def normalize(q: tuple[float, ...]) -> tuple[float, ...]:
    n = norm(q)
    return tuple(x / n for x in q)


def centroid(points: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]:
    base = points[0]
    aligned = []
    for q in points:
        if dot(q, base) < 0.0:
            aligned.append(tuple(-x for x in q))
        else:
            aligned.append(q)
    mean = tuple(sum(q[i] for q in aligned) / len(aligned) for i in range(4))
    return normalize(mean)


def dist(a: tuple[float, ...], b: tuple[float, ...]) -> float:
    return norm(tuple(x - y for x, y in zip(a, b)))


def hopf_lapse(q: tuple[float, float, float, float]) -> float:
    a, b, c, d = q
    vv = (a * a + b * b) - (c * c + d * d)
    return math.sqrt(max(0.0, 1.0 - vv * vv))


e0 = (1.0, 0.0, 0.0, 0.0)
e1 = (0.0, 1.0, 0.0, 0.0)
e2 = (0.0, 0.0, 1.0, 0.0)
direct_three = centroid([e0, e1, e2])
staged_three = centroid([centroid([e0, e1]), e2])

v.check("Omega monad", OMEGA, 137.036, rel=3e-6)
v.check("FRAC_EDGE", FRAC_EDGE, 0.02289, rel=2e-3)
v.check("FRAC_BOUNDARY", FRAC_BOUNDARY, 0.072, rel=4e-4)
v.check("FRAC_BULK", FRAC_BULK, 0.905, rel=6e-5)
v.check("layer fractions sum", FRAC_EDGE + FRAC_BOUNDARY + FRAC_BULK, 1.0, rel=1e-12)
v.check("plateau threshold / edge fraction", PLATEAU_THRESHOLD / FRAC_EDGE, 0.874, rel=3e-3)
v.check("derived threshold relaxes 0.02 by percent", 100.0 * (FRAC_EDGE - PLATEAU_THRESHOLD) / PLATEAU_THRESHOLD, 15.0, rel=3e-2)
v.check("BREATH_PERIOD", BREATH_PERIOD, 430.5, rel=3e-5)
v.check("stale cutoff 2*BREATH_PERIOD", 2.0 * BREATH_PERIOD, 861.0, rel=3e-4)
v.check("singleton centroid returns q", dist(centroid([e0]), e0), 0.0, abs_tol=1e-12)
v.check("hopf_lapse identity quaternion", hopf_lapse(e0), 0.0, abs_tol=1e-12)
v.check("hopf_lapse pure c quaternion", hopf_lapse(e2), 0.0, abs_tol=1e-12)
v.check("hopf_lapse mixed Hopf equator", hopf_lapse(normalize((1.0, 0.0, 1.0, 0.0))), 1.0, rel=1e-12)

v.record(
    "P34 correctly flags delta_P as calibration",
    "not geometrically derived" in TEX and "calibration parameter" in TEX,
    computed="threshold status caveat found",
    claimed="PLATEAU_THRESHOLD is calibration, not a frozen constant",
)
v.record(
    "referenced implementation files are present in this TOE workspace",
    all((WORKSPACE / p).exists() for p in ["Ged/ged/wheel.py", "Ged/ged/flush.py", "Lumen/muaddib.py"]),
    computed="checked Ged/ged/wheel.py, Ged/ged/flush.py, Lumen/muaddib.py under the current workspace",
    claimed="monad laws verified against existing implementation functions",
    detail="Expected reproducibility fail in this paper folder: the cited code is not present here.",
)
v.record(
    "left identity holds for arbitrary f:S3->T(S3)",
    False,
    computed="if f(q)={(e0,.5),(e1,.5)}, the displayed bind applies eta to the weighted union and collapses it to the centroid, not the original two-point distribution",
    claimed="eta(q) bind f = f(q) for all Kleisli morphisms",
    detail="Expected monad-law fail for non-point outputs.",
)
v.record(
    "right identity preserves a non-degenerate distribution",
    False,
    computed=f"m={{e0,e1}} collapses to centroid {centroid([e0, e1])}, losing the original two support points",
    claimed="m bind eta = m for all m in T(S3)",
    detail="Expected monad-law fail under centroid-collapse semantics.",
)
v.record(
    "centroid-collapse associativity holds for nested averages",
    dist(direct_three, staged_three) < 1e-12,
    computed=f"direct={direct_three}, staged={staged_three}, Euclidean gap={dist(direct_three, staged_three):.6f}",
    claimed="nested geodesic centroids commute by linearity",
    detail="Expected associativity fail: normalization after the first centroid changes the weights.",
)
v.record(
    "extrinsic mean laws are exact for all hemisphere-confined distributions",
    False,
    computed="hemisphere sign-alignment removes the double-cover ambiguity, but centroid collapse still loses distribution support and intermediate normalization changes weights",
    claimed="monad laws hold exactly when points lie in one hemisphere",
    detail="Expected scope fail.",
)
v.record(
    "plateau condition is a categorical fixpoint at Omega",
    False,
    computed="plateau checks convergence flags or small recent MDL spread; it does not prove equality to the attractor Omega or a categorical fixed point",
    claimed="WheelState has reached a fixpoint/is at Omega when plateau returns True",
    detail="Expected proof-status fail.",
)
v.record(
    "no learned weights follows from the displayed kernel alone",
    False,
    computed="the kernel is fixed, but fork/weld still depend on proposal generation, orientation, layer labels, thresholds, and code-level choices",
    claimed="attention has no fitted parameters because hopf_lapse replaces QK^T",
    detail="Expected scope fail.",
)
v.record(
    "no-free-parameters categorical invariant claim is supported",
    False,
    computed="the paper itself identifies PLATEAU_THRESHOLD=0.02 as a calibration parameter and references implementation choices",
    claimed="Kleisli composition cannot introduce new scales / no free parameters",
    detail="Expected status fail.",
)

sys.exit(v.summary())
