#!/usr/bin/env python3
"""
verify_P171.py -- G1 modular residual addendum.

The file is named 171_Addendum_G1ModularResidual.tex but its TeX header/title
calls it Addendum 167. This verifier reproduces the G1/j(i) arithmetic and
flags metadata/proof-scope issues not covered by the older verify_G1_modular.py
script.
"""

from __future__ import annotations

import sys
from pathlib import Path

from mpmath import mp

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("P171 -- G1 Modular Residual")

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

mp.dps = 80
PI = mp.pi
ALPHA_INV = 4 * PI**3 + PI**2 + PI
OMEGA = PI * ALPHA_INV
J_I = mp.mpf(1728)
J_SHORT = mp.mpf(12)
G1 = (mp.mpf(432) - OMEGA) / OMEGA
G1_J = J_I / (4 * OMEGA) - 1
GAP = J_I - 4 * OMEGA
DEFICIT = J_SHORT / 2 - GAP
FOUR_OMEGA_POLY = 16 * PI**4 + 4 * PI**3 + 4 * PI**2


def fmt(x: mp.mpf, digits: int = 18) -> str:
    return mp.nstr(x, digits)


v.check("alpha inverse", float(ALPHA_INV), 137.036303776, rel=2e-9)
v.check("Omega breath period", float(OMEGA), 430.5122452173989, rel=2e-15)
v.check("G1 definition", float(G1), 0.00345577808559148, rel=2e-14)
v.check("j(i)/4", float(J_I / 4), 432.0, rel=0)
v.check("J_short^3", float(J_SHORT**3), 1728.0, rel=0)
v.check("G1 j-formula", float(G1_J), float(G1), rel=1e-15)
v.check("Omega reconstruction", float(J_I / (4 * (1 + G1))), float(OMEGA), rel=1e-15)
v.check("absolute gap j(i)-4Omega", float(GAP), 5.951019130404289, rel=2e-15)
v.check("near miss is below 6", float(GAP), 6.0, rel=1e-2)
v.check("deficit", float(DEFICIT), 0.04898086959571096, rel=2e-14)
v.check("4Omega polynomial identity", float(4 * OMEGA), float(FOUR_OMEGA_POLY), rel=1e-15)
v.check("4Omega = S2 area * alpha_inv", float(4 * OMEGA), float(4 * PI * ALPHA_INV), rel=1e-15)
v.check("tau(3)/432", 252.0 / 432.0, 7.0 / 12.0, rel=0)
v.check("pi^2/200 near deficit", float((PI**2 / 200) / DEFICIT), 1.0, rel=8e-3)
v.record(
    "G1 is positive",
    G1 > 0 and OMEGA < 432,
    computed=f"Omega={fmt(OMEGA)}, G1={fmt(G1)}",
    claimed="Omega < 432 and G1 > 0",
)
v.record(
    "near-miss non-exactness follows numerically",
    abs(GAP - 6) > mp.mpf("1e-20"),
    computed=f"6-gap={fmt(DEFICIT)}",
    claimed="j(i)-4Omega is not exactly 6",
)
v.record(
    "older verifier script is referenced",
    "verify\\_G1\\_modular.py" in TEX,
    computed="TeX references verify_G1_modular.py",
    claimed="55-significant-figure verification available",
)

v.record(
    "file number and addendum number agree",
    "Addendum 171" in TEX or "P171" in TEX,
    computed="file is 171_Addendum_G1ModularResidual.tex, but header/title say Addendum 167 / P167",
    claimed="paper numbering is P171",
    detail="Expected metadata fail.",
)
v.record(
    "432 is literally the nearest integer to Omega",
    round(float(OMEGA)) == 432,
    computed=f"Omega={fmt(OMEGA)} rounds to {round(float(OMEGA))}",
    claimed="432 is the nearest integer to Omega",
    detail="Expected wording fail if read literally; 432 is the modular reference, not the nearest integer.",
)
v.record(
    "no modular form of any kind can evaluate to 4Omega at tau=i",
    False,
    computed="the proof only covers modular forms/special values with algebraic Fourier coefficients; arbitrary transcendental scalar multiples can force transcendental values",
    claimed="no modular form f for SL(2,Z) evaluates to 4Omega at tau=i",
    detail="Expected scope fail.",
)
v.record(
    "CM special values at tau=i are exactly powers j(i)^(k/n)",
    False,
    computed="the set {j(i)^(k/n)} is a narrow family of algebraic numbers, not the full ring/field of CM modular-form values",
    claimed="equivalently, 4Omega is outside {j(i)^(k/n)}",
    detail="Expected equivalence/scope fail.",
)

sys.exit(v.summary())
