#!/usr/bin/env python3
"""
verify_P112.py -- Addendum 112: G2 x 2I product formula for sin^2(theta_W).

This verifier checks the corrected character-average calculation, the exact
3/(8phi) product formula, the 600-cell f-vector group ratios, and the
perturbative S(lambda) convergence table. It flags the remaining proof-status
issues around the G2 "non-singlet fraction" interpretation and the still-open
5B selection rule.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

PASS = FAIL = 0
_N = 0


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


class Verifier:
    """Same check semantics as verify_common.Verifier; modern output style."""

    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 = abs(computed - claimed)
            err_detail = f"abs err={err:.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=""):
        check(label + (f" -- {detail}" if detail else ""), ok)
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        return ok

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


v = Verifier("P112 -- Weinberg Exact v2")

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

PI = math.pi
PHI = (1.0 + math.sqrt(5.0)) / 2.0
TAU = 1.0 / PHI
TARGET = 3.0 / (8.0 * PHI)
S_TARGET = (1.0 + PI) * TARGET
LAM = math.sin(PI / 14.0)

class_sizes = [1, 1, 30, 20, 20, 12, 12, 12, 12]
chi2 = [2.0, -2.0, 0.0, -1.0, 1.0, PHI, -PHI, TAU, -TAU]
sym2_chars = [c * c - 1.0 for c in chi2]
avg_sym2 = sum(s * c for s, c in zip(class_sizes, sym2_chars)) / sum(class_sizes)
avg_v2 = sum(s * c for s, c in zip(class_sizes, chi2)) / sum(class_sizes)

S_c2 = 1.0 - (4.0 / 5.0) * LAM**2
S_c2c6 = S_c2 - (24.0 / 5.0) * LAM**6
S_c2c6c8 = S_c2c6 + 8.0 * LAM**8
Q_LIMIT = (1.0 - S_TARGET) * 5.0 / (4.0 * LAM**2)


def rel_gap(value: float, target: float = S_TARGET) -> float:
    return 100.0 * (value - target) / target


v.check("binary icosahedral class sizes sum", sum(class_sizes), 120, rel=0)
v.check("phi", PHI, 1.61803398875, rel=1e-12)
v.check("tau=1/phi", TAU, 0.61803398875, rel=1e-12)
v.check("average V2 character", avg_v2, 0.0, abs_tol=1e-12)
v.check("average Sym^2(V2) character", avg_sym2, 0.0, abs_tol=1e-12)
v.record(
    "P111 Molien/orbit-average error is corrected",
    "correct value is zero" in TEX and "Schur" in TEX,
    computed=f"Sym^2 average={avg_sym2:.3g}",
    claimed="non-trivial irrep character average vanishes",
)

v.check("G2 factor 3/4", 3.0 / 4.0, 0.75, rel=0)
v.check("chi2(5B)", TAU, 1.0 / PHI, rel=1e-12)
v.check("2I factor tau/2", TAU / 2.0, math.cos(2.0 * PI / 5.0), rel=1e-12)
v.check("product formula", (3.0 / 4.0) * (TAU / 2.0), TARGET, rel=1e-12)
v.check("sin^2 theta_W target value", TARGET, 0.23176, rel=2e-5)
v.check("target residual vs PDG percent", 100.0 * (TARGET - 0.23122) / 0.23122, 0.24, rel=3e-2)

v.check("600-cell V/V", 120.0 / 120.0, 1.0, rel=0)
v.check("600-cell E/V", 720.0 / 120.0, 6.0, rel=0)
v.check("600-cell F/V", 1200.0 / 120.0, 10.0, rel=0)
v.check("600-cell C/V", 600.0 / 120.0, 5.0, rel=0)
v.check("|W(G2)|/2", 12.0 / 2.0, 6.0, rel=0)
v.check("|2I|/|W(G2)|", 120.0 / 12.0, 10.0, rel=0)
v.check("|2I|/(2|W(G2)|)", 120.0 / (2.0 * 12.0), 5.0, rel=0)

v.check("lambda^2", LAM**2, 0.0495156, rel=7e-7)
v.check("S target", S_TARGET, 0.95987, rel=4e-6)
v.check("Q(lambda^2) limit", Q_LIMIT, 1.01314, rel=4e-6)
v.check("S NLO", S_c2, 0.96039, rel=3e-6)
v.check("S NLO gap", abs(S_c2 - S_TARGET), 5.21e-4, rel=3e-3)
v.check("S NNNLO", S_c2c6, 0.95980, rel=6e-6)
v.check("S NNNLO gap", abs(S_c2c6 - S_TARGET), 6.21e-5, rel=6e-4)
v.check("S NNNNLO", S_c2c6c8, 0.95985, rel=4e-6)
v.check("S NNNNLO gap", abs(S_c2c6c8 - S_TARGET), 1.40e-5, rel=2e-3)
v.check("NLO relative gap", rel_gap(S_c2), 0.054, rel=5e-3)
v.check("NNNLO relative gap", rel_gap(S_c2c6), -0.0065, rel=6e-3)
v.check("NNNNLO relative gap", rel_gap(S_c2c6c8), -0.0015, rel=3e-2)

v.record(
    "stratum-sum circularity is explicitly left open",
    "uses the product-formula value" in TEX and "close this circle" in TEX,
    computed="open-status caveat found",
    claimed="direct proof of bracket-limit series remains open",
)
v.record(
    "selection rule is explicitly left open",
    "Selection rule" in TEX and "is stated but not derived" in TEX,
    computed="5B physical-selection caveat found",
    claimed="selection of 5B still requires J3(O)/Peirce analysis",
)
v.record(
    "F4-covariant c4 proof is explicitly left open",
    "full $F_4$-covariant proof is still open" in TEX,
    computed="c4 covariance caveat found",
    claimed="P111 c4 result not fully F4-covariant here",
)

v.check(
    "ordinary non-singlet dimension fraction in 7-rep",
    6.0 / 7.0,
    3.0 / 4.0,
    rel=1e-12,
    detail="Expected interpretation fail: 3/4 counts three short-root pairs plus one singlet, not dimensions of the 7-dimensional weight space.",
)
v.record(
    "hypercharge lies entirely in the short-root weight space is derived here",
    False,
    computed="the paper states the identification with electroweak hypercharge/generations but does not construct H_Y in J3(O) or its projection",
    claimed="H_Y lies entirely in the short-root non-singlet space",
    detail="Expected proof-status fail.",
)
v.record(
    "5B is selected from first principles",
    False,
    computed="the summary explicitly says the physical argument for 5B rather than 5A/10A/10B is not derived",
    claimed="f_2I = chi2(5B)/2 from the physical selection rule",
    detail="Expected status fail.",
)
v.record(
    "Conjecture P105-1 is unconditionally proved",
    False,
    computed="the status paragraph says P105-1 is a theorem only conditional on the selection-rule derivation",
    claimed="sin^2 theta_W all-orders theorem without residual conditions",
    detail="Expected status fail.",
)

sys.exit(v.summary())
