#!/usr/bin/env python3
"""
verify_P031.py -- Paper 31: Nicomachus weights and monad closure.

This verifier checks the explicit count/factorisation arithmetic in
31_Paper_NicomachusMonad.tex and audits the later claim that the Bézout/Hopf
mechanism fully resolves the Paper 08 counting proof gap.
"""

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 output adapter: inherits Verifier's tolerance logic unchanged,
    emits the corpus's modern check-line format (numbered [PASS]/[FAIL]
    lines, computed/claimed as indented info lines)."""

    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)
        desc = label if (ok or not detail) else f"{label} -- {detail}"
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if ok and detail:
            print(f"        {detail}")
        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("P031 -- Nicomachus Monad Closure")

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

PI = math.pi
OMEGA = 4.0 * PI**3 + PI**2 + PI
ALPHA_INV_CODATA = 137.035999084


def positive_part(x: int) -> int:
    return max(x, 0)


def c_formula(d: int) -> int:
    return (d + 1) ** max(d - 1, 1)


def screened_coeff(d: int) -> int:
    return (d + 1) ** positive_part(d - 2)


def cheb_roots(k: int) -> list[float]:
    return [math.cos(math.pi * (2 * m + 1) / (2 * k)) for m in range(k)]


v.check("Omega monad sum", OMEGA, 137.036303776, rel=2e-9)
v.check("Omega vs CODATA alpha inverse relative percent", 100.0 * (OMEGA - ALPHA_INV_CODATA) / ALPHA_INV_CODATA, 0.000222, rel=2e-3)
v.check("density integral d=1 contribution", 2.0 * PI / 2.0, PI, rel=1e-12)
v.check("density integral d=2 contribution", 3.0 * PI**2 / 3.0, PI**2, rel=1e-12)
v.check("density integral d=3 contribution", 16.0 * PI**3 / 4.0, 4.0 * PI**3, rel=1e-12)
v.check("factored monad d=1", screened_coeff(1) * PI, PI, rel=1e-12)
v.check("factored monad d=2", screened_coeff(2) * PI**2, PI**2, rel=1e-12)
v.check("factored monad d=3", screened_coeff(3) * PI**3, 4.0 * PI**3, rel=1e-12)

for d, expected in [(1, 2), (2, 3), (3, 16)]:
    k = d + 1
    v.check(f"c_d formula d={d}", c_formula(d), expected, rel=0)
    v.check(f"c_d/k screened coefficient d={d}", c_formula(d) / k, screened_coeff(d), rel=0)
    v.check(f"offset identity d={d}", positive_part(d - 2) + 1, max(d - 1, 1), rel=0)
    v.check(
        f"Hopf exponent sum d={d}",
        positive_part(d - 2) + 1 + min(4 - d, 2),
        3,
        rel=0,
    )
    v.check(
        f"k^3 factorization d={d}",
        k ** positive_part(d - 2) * k * k ** min(4 - d, 2),
        k**3,
        rel=0,
    )

v.check("Nicomachus cubes 1^3+2^3+3^3+4^3", sum(j**3 for j in range(1, 5)), sum(range(1, 5)) ** 2, rel=0)
v.check("d=3 dynamic count", 4**2, 16, rel=0)
v.check("d=3 static count", 2**4, 16, rel=0)
v.check("d=3 static count divided by k", (2**4) / 4, 4, rel=0)

for k in (2, 3, 4):
    roots = cheb_roots(k)
    v.record(
        f"Chebyshev T_{k} has k real roots in (-1,1)",
        len(roots) == k and all(-1.0 < r < 1.0 for r in roots) and len({round(r, 14) for r in roots}) == k,
        computed=", ".join(f"{r:.6f}" for r in roots),
        claimed=f"{k} distinct real roots",
    )

v.record(
    "initial conditional status is acknowledged",
    "conditional on Paper~08's counting values" in TEX and "remain open" in TEX,
    computed="the early paper explicitly treats the uniform mechanism as open",
    claimed="main theorem initially conditional",
)
v.record(
    "resolution section claims the open problem is closed",
    "Open Problem of \\S\\ref{sec:openproblem} is fully resolved" in TEX
    and "FRAME-AXIOM is no longer an asserted conjecture" in TEX,
    computed="resolution claim found",
    claimed="Bézout mechanism closes the frame axiom",
)

v.record(
    "Hopf modulus dimension is derived from explicit self-intersection equations",
    False,
    computed="the proof counts sheet phases and imposes a holonomy constraint, but no explicit local model for psi^{-1}(0) or the stratum equations is supplied",
    claimed="modulus dimension n=max(d-1,1)",
    detail="Expected proof-status fail.",
)
v.record(
    "Z_k monodromy is proved as stratum-linking monodromy",
    False,
    computed="Z2/Z3/Z4 subgroup actions are identified, but the loop linking each self-intersection stratum and its induced monodromy are not constructed",
    claimed="monodromy around any stratum-linking loop is exp(2pi i/k)",
    detail="Expected topology proof fail.",
)
v.record(
    "degree-k Chebyshev frame equation follows from the Hopf bundle proof",
    False,
    computed="the proof moves from c1(H^k)=k and section zeros on S2 to a per-fibre equation T_k(t)=0 without deriving the frame condition or quotienting the two S1 phases per t-root",
    claimed="each modulus coordinate obeys T_k(t_j)=0",
    detail="Expected derivation fail.",
)
v.record(
    "Bézout count is an independently derived configuration count",
    False,
    computed="once n=max(d-1,1) and decoupled T_k equations are assumed, k^n is immediate; those assumptions are the substantive unproved part",
    claimed="c_d is derived from first principles by Bézout",
    detail="Expected proof-status fail.",
)
v.check(
    "static 2^4 factorization would give weight 2^3",
    (2**4) / 4.0,
    2**3,
    rel=0,
    detail="Expected internal fail: using the paper's own integration factor 1/k with k=4 gives 16/4=4, not 8.",
)
v.record(
    "monad identity independently selects the dynamic mechanism without circularity",
    False,
    computed="the argument uses agreement with the target Omega to prefer the dynamic 4^2 reading over the static 2^4 reading",
    claimed="Omega independently confirms the dynamic mechanism",
    detail="Expected proof-status/circularity fail.",
)
v.record(
    "first-principles unconditional closure is warranted",
    False,
    computed="the resolution still depends on imported lens-space/Hopf-action identifications and unproved stratum-to-frame equations",
    claimed="derivation of Omega=alpha^{-1} from first principles unconditionally",
    detail="Expected status fail.",
)

sys.exit(v.summary())
