#!/usr/bin/env python3
"""
verify_P000.py -- Paper 0: Monad Rosetta Map.

Paper 0 is explicitly a cross-reference map, not a completed derivation.  This
verifier checks the reusable density arithmetic and flags claims that overstate
what is formally defined in this TeX.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

PASS = FAIL = 0
_N = 0


def check(n, desc, cond):
    global PASS, FAIL
    ok = bool(cond); PASS += ok; FAIL += (not ok)
    print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
    return ok


class Verifier:
    """Target-style output adapter; check/record numerics are unchanged."""

    def __init__(self, name):
        print(name)

    def check(self, label, computed, claimed, *, rel=1e-3, abs_tol=None, detail=""):
        if abs_tol is not None:
            ok = abs(computed - claimed) <= abs_tol
            err_detail = f"abs err={abs(computed - claimed):.6g}, tol={abs_tol:.6g}"
        else:
            if claimed == 0:
                ok = abs(computed) <= (rel or 1e-12)
                err_detail = f"abs value={abs(computed):.6g}, tol={rel:.6g}"
            else:
                err = (computed - claimed) / abs(claimed)
                ok = abs(err) <= (rel or 0)
                err_detail = f"rel err={100 * err:+.6g}%, tol={100 * (rel or 0):.6g}%"
        return self.record(label, ok, computed, claimed,
                           err_detail + (f"; {detail}" if detail else ""))

    def record(self, label, ok, computed="", claimed="", detail=""):
        global _N
        ok = bool(ok)
        desc, extra = label, detail
        if not ok and detail:
            desc, extra = f"{label} -- {detail}", ""
        _N += 1
        check(_N, desc, ok)
        if computed != "" or claimed != "":
            print(f"       computed: {computed}")
            print(f"       claimed : {claimed}")
        if extra:
            print(f"       {extra}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
        return 1 if FAIL else 0


v = Verifier("P000 -- Monad Rosetta Map")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "00_Paper_MonadRosettaMap.tex").read_text()

PI = math.pi
ALPHA_INV_CODATA = 137.035999084


def rel_percent(value: float, target: float) -> float:
    return 100.0 * (value - target) / abs(target)


omega = 4.0 * PI**3 + PI**2 + PI

v.record("TeX source is present", "Rosetta map" in TEX or "Rosetta Map" in TEX)
v.check("bulk density integral", 16.0 * PI**3 / 4.0, 4.0 * PI**3, rel=1e-15)
v.check("boundary density integral", 3.0 * PI**2 / 3.0, PI**2, rel=1e-15)
v.check("observation density integral", 2.0 * PI / 2.0, PI, rel=1e-15)
v.check("monad density integral", omega, 137.036304, rel=3e-9)
v.check("lambda fixed by G4 target", omega / (4.0 * PI**3 + PI**2 + PI), 1.0, rel=1e-15)
v.record(
    "density lies in P3^0",
    True,
    computed="rho(x)=16*pi^3*x^3+3*pi^2*x^2+2*pi*x has no constant term",
    claimed="rho in P3^0",
)
v.record(
    "degree <= 2 cannot include mandatory bulk x^3 term",
    True,
    computed="a nonzero 16*pi^3*x^3 term requires degree at least 3",
    claimed="cubic degree is minimal under the three-layer grading",
)
v.check("three layers over four-dimensional bulk", 3.0 / 4.0, 0.75, rel=0)
v.record(
    "division-algebra sphere dimensions",
    [0, 1, 3, 7] == [1 - 1, 2 - 1, 4 - 1, 8 - 1],
    computed="R,C,H,O have real dimensions 1,2,4,8 and unit spheres S0,S1,S3,S7",
    claimed="S0,S1,S3,S7 division-algebra backbone",
)
v.record(
    "abstract three-cycle has order three once defined as a 3-cycle",
    True,
    computed="bulk -> boundary -> fiber -> bulk is a 3-cycle by definition",
    claimed="T^3=I at the structural level",
)
v.record(
    "lens-space Z3 family pointer is topologically plausible",
    True,
    computed="L(3,1)=S3/Z3 has a cyclic deck group/fundamental group of order 3",
    claimed="same Z3 structure arises topologically in L(3,1)",
)

v.record(
    "geometric omega equals physical alpha inverse exactly",
    False,
    computed=f"4*pi^3+pi^2+pi={omega:.12f}, CODATA alpha^-1={ALPHA_INV_CODATA:.12f}, rel diff={rel_percent(omega, ALPHA_INV_CODATA):+.6g}%",
    claimed="4*pi^3+pi^2+pi = alpha^{-1}",
    detail="Expected fail: the geometric value is a close approximation, not exact equality to CODATA alpha inverse.",
)
v.record(
    "limit-normalization operator R is formally specified here",
    False,
    computed="the paper explicitly calls R a conceptual placeholder with no domain, codomain, or algebraic rule in this document",
    claimed="limit-equivalence definition can serve as a standalone derivation",
    detail="Expected formal-status fail.",
)
v.record(
    "C and P are defined enough to prove C o P = I consequences",
    False,
    computed="C and P are formal names for collapse/projection on an unspecified state space; no maps or admissible states are supplied",
    claimed="fundamental interaction identity C o P = I",
    detail="Expected operator-definition fail.",
)
v.record(
    "representation dimensions 16, 3, 2 are derived in P0",
    False,
    computed="16, 3, and 2 are assigned to bulk, boundary, and edge structures, but the representation spaces/actions are not constructed here",
    claimed="16,3,2 are representation dimensions of the three structures",
    detail="Expected derivation-status fail.",
)
v.record(
    "electron mass is completely determined by supplied data",
    False,
    computed="the mass mapping is labelled a working hypothesis and the eigenvalue spectrum of O has not been computed",
    claimed="electron mass and scale are completely determined by geometric data",
    detail="Expected internal-status fail.",
)
v.record(
    "master operator is mathematically specified",
    False,
    computed="the operator is a blueprint with unspecified function spaces, domains, self-adjointness, compactness, and concrete definitions of T, R*, M[rho]",
    claimed="master operator blueprint generates the spectral data",
    detail="Expected specification fail.",
)
v.record(
    "T^3=I is proved for a concrete layer-cycle operator",
    False,
    computed="the bulk/boundary/fiber maps are named but not defined as operators on a common Hilbert space",
    claimed="by construction, T has order three",
    detail="Expected formalization fail.",
)
v.record(
    "phenomenological consciousness/singularity claims are mathematical consequences",
    False,
    computed="the Rosetta map gives interpretations, not definitions or derivations connecting these phenomena to C o P = I",
    claimed="singularities and consciousness are manifestations of the same interaction identity",
    detail="Expected non-formal-claim fail.",
)
v.record(
    "referenced Ged wheel implementation is present in TOE workspace",
    (ROOT / "Ged" / "ged" / "wheel.py").exists(),
    computed="TOE/Ged/ged/wheel.py not found",
    claimed="plateau() in Ged/ged/wheel.py realizes the attractor computationally",
    detail="Expected reproducibility fail if the code is not included in this workspace.",
)
v.record(
    "identity plus C o P suffices to generate the entire TOE structure",
    False,
    computed="the conclusion itself says this is a reference document, not a completed derivation, and later work must specify O and connect to QFT/GR",
    claimed="the identities suffice to organize and generate the entire geometric ToE structure",
    detail="Expected overstatement fail.",
)

sys.exit(v.summary())
