#!/usr/bin/env python3
"""
verify_P051.py -- Addendum 51: X_sector as canonical J3(O) diagonal.

This verifier checks the sector-density integrals, Xsec/Xone trace chain,
harmonic diagonal moment hierarchy, K mean-coordinate matrix, spectral-log
rewrites, and the mass-map logarithm formulas in
51_Addendum_XsectorCanonical.tex.

Most arithmetic checks pass. The flagged issues are proof/status issues:
the paper sometimes calls the sector powers n_i=1,2,3 the cell dimensions,
but the cells listed are S1, S3, B4 with dimensions 1,3,4; the
sector-idempotent bijection is presented as determined by G2-orbit structure
while the stronger T2 uniqueness theorem is explicitly open; and the final
mass-ratio step m_t/m_c=Tr(Xsec) remains OP-B-Mass rather than a derived
consequence of the trace identity.
"""

from __future__ import annotations

import math
import sys
from itertools import permutations
from pathlib import Path

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


class Verifier(_BaseVerifier):
    """Output-layer normalization only: same checks, modern [PASS]/[FAIL] format."""

    def __init__(self, name: str):
        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)
        note, info = "", detail
        if not ok and "Expected" in detail:
            i = detail.find("Expected")
            note = " -- " + detail[i:]
            info = detail[:i].rstrip().rstrip(";")
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {label}{note}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        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 = Verifier("P051 -- X_sector Canonical Diagonal")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "51_Addendum_XsectorCanonical.tex").read_text()

PI = math.pi
M_E = 0.51099895


def mu(k: int) -> float:
    return 16.0 * PI**3 / (k + 4.0) + 3.0 * PI**2 / (k + 3.0) + 2.0 * PI / (k + 2.0)


def d_entry(n: int, k: int) -> float:
    return (n + 1.0) / (k + n + 1.0)


MU0 = mu(0)
MU1 = mu(1)
MU = MU1 / MU0

sector_powers = (1, 2, 3)
cell_dimensions = (1, 3, 4)
sector_coefficients = (PI, PI**2, 4.0 * PI**3)
XSEC = sector_coefficients
K = tuple((n + 1.0) / (n + 2.0) for n in sector_powers)
XONE = tuple(XSEC[i] * K[i] for i in range(3))

v.check("mu0", MU0, 137.036304, rel=2e-9)
v.check("mu1", MU1, 108.716684, rel=3e-9)
v.check("MU", MU, 0.793342, rel=3e-7)
v.check("rank J3(O)", 3, 3, rel=1e-12)
v.check("dimension J3(O)", 27, 27, rel=1e-12)

v.check("edge sector integral", 2.0 * PI / (sector_powers[0] + 1.0), PI, rel=1e-12)
v.check("boundary sector integral", 3.0 * PI**2 / (sector_powers[1] + 1.0), PI**2, rel=1e-12)
v.check("bulk sector integral", 16.0 * PI**3 / (sector_powers[2] + 1.0), 4.0 * PI**3, rel=1e-12)
v.check("sum sector energies", sum(sector_coefficients), MU0, rel=1e-12)
v.check("Tr(Xsec)", sum(XSEC), MU0, rel=1e-12)
v.check("K_1 mean coordinate", K[0], 2.0 / 3.0, rel=1e-12)
v.check("K_2 mean coordinate", K[1], 3.0 / 4.0, rel=1e-12)
v.check("K_3 mean coordinate", K[2], 4.0 / 5.0, rel=1e-12)
v.check("Tr(Xsec circ K)", sum(XONE), MU1, rel=1e-12)

v.record(
    "sector powers n_i are literal cell dimensions",
    sector_powers == cell_dimensions,
    computed=f"sector powers={sector_powers}, listed cell dimensions={cell_dimensions}",
    claimed="sector densities determined by cell dimension n_i",
    detail="Expected wording/formula fail: the exponents are 1,2,3, while S1/S3/B4 have dimensions 1,3,4. The exponents are not literal cell dimensions.",
)

for k in range(0, 8):
    dk = tuple(d_entry(n, k) for n in sector_powers)
    trace = sum(XSEC[i] * dk[i] for i in range(3))
    v.check(f"moment hierarchy k={k}", trace, mu(k), rel=1e-12)

for k, expected in [
    (0, (1.0, 1.0, 1.0)),
    (1, (2.0 / 3.0, 3.0 / 4.0, 4.0 / 5.0)),
    (2, (1.0 / 2.0, 3.0 / 5.0, 2.0 / 3.0)),
]:
    dk = tuple(d_entry(n, k) for n in sector_powers)
    v.record(f"D_{k} entries", all(abs(dk[i] - expected[i]) < 1e-12 for i in range(3)), computed=dk, claimed=expected)

v.record(
    "only sorted sector-idempotent permutation respects powers and cell dimensions",
    sum(
        1
        for perm in permutations(range(3))
        if all(sector_powers[perm[i]] <= sector_powers[perm[i + 1]] for i in range(2))
        and all(cell_dimensions[perm[i]] <= cell_dimensions[perm[i + 1]] for i in range(2))
    )
    == 1,
    computed="unique order by powers and dimensions is edge, boundary, bulk",
    claimed="any permutation violates the ordering condition",
)

g0 = math.log(sum(XSEC)) / MU
g1 = math.log(sum(XONE)) / MU
v.check("spectral-log G0", g0, math.log(MU0) / MU, rel=1e-12)
v.check("spectral-log G1", g1, math.log(MU1) / MU, rel=1e-12)
v.check("G0-G1 spectral-log gap", g0 - g1, -math.log(MU) / MU, rel=1e-12)

def mass_map(e: float) -> float:
    return math.exp(MU * (e - PI))


def mass_map_inverse(r: float) -> float:
    return PI + math.log(r) / MU


v.check("mass-map inverse at mu0 minus pi", mass_map_inverse(MU0) - PI, math.log(MU0) / MU, rel=1e-12)
v.check("mass-map inverse at mu1 minus pi", mass_map_inverse(MU1) - PI, math.log(MU1) / MU, rel=1e-12)
v.check("mass-map round trip", mass_map(mass_map_inverse(MU0)), MU0, rel=1e-12)

ed = math.log(MU1) / MU
md = M_E * math.exp(MU * (ed - PI))
v.check("E_d spectral-log formula", ed, 5.9101, rel=5e-6)
v.check("down mass from E_d", md, 4.595, rel=4e-5)

v.record(
    "sector-idempotent bijection is a completed algebraic theorem",
    "OP-B-T2" not in TEX and "T2 is open" not in TEX,
    computed="P51 calls T2 uniqueness open and describes Proposition 3.1 as a natural-correspondence argument",
    claimed="bijection is determined by G2-orbit structure",
    detail="Expected proof-status fail: the natural ordering is plausible, but the formal F4/G2 uniqueness theorem remains open in the paper.",
)
v.record(
    "m_t/m_c = Tr(Xsec) is derived from the canonical trace identity",
    "OP-B-Mass" not in TEX,
    computed="P51 says the mass-ratio-from-spectral-trace step is still open",
    claimed="Conjecture B as structural spectral-log statement",
    detail="Expected status fail: Xsec is better motivated, but the top/charm mass-ratio link is not derived.",
)
v.record(
    "Conjecture D is fully structural after P51",
    "reduces to OP-B-Mass" not in TEX,
    computed="P51 says Conjecture D reduces to OP-B-Mass plus a JO-intrinsic identification of -ln(MU)/MU",
    claimed="Conjecture D spectral-log statement",
    detail="Expected status fail: the formula is exact, but structural closure is explicitly conditional.",
)

sys.exit(v.summary())
