#!/usr/bin/env python3
"""
verify_P111.py -- Addendum 111: claimed exact Weinberg angle.

This verifier checks the numerical 600-cell subseries and the two central
proof mechanisms in 111_Addendum_WeinbergExact.tex:

* the printed Freudenthal cross-product formula on diagonal elements;
* the binary-icosahedral/Molien fixed-point identity;
* the S-series convergence table and master prediction table.

Several rounded 600-cell subseries values reproduce, but the central proof
has hard failures: the diagonal Freudenthal triple-product lemma is false
under the paper's own cross-product formula, the finite-group character
average sketch cannot by itself produce a pi-dependent factor, and the paper
remains explicitly conditional while claiming theorem status.
"""

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 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("P111 -- Weinberg Exact Claim")

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

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


def gap_pct_s(s: float) -> float:
    return 100.0 * (s - S_TARGET) / S_TARGET


def cross_diag(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]:
    tr_a = sum(a)
    tr_b = sum(b)
    prod = tuple(a[i] * b[i] for i in range(3))
    tr_prod = sum(prod)
    scalar = 0.5 * (tr_a * tr_b - tr_prod)
    return tuple(
        prod[i] - 0.5 * tr_a * b[i] - 0.5 * tr_b * a[i] + scalar
        for i in range(3)
    )


def freudenthal_T_diag(x: tuple[float, float, float]) -> tuple[float, float, float]:
    xx = cross_diag(x, x)
    return tuple(0.5 * y for y in cross_diag(xx, x))


def det_diag(x: tuple[float, float, float]) -> float:
    return x[0] * x[1] * x[2]


S_c2 = 1.0 - (4.0 / 5.0) * LAM**2
S_full_c2c4 = 1.0 - (4.0 / 5.0) * LAM**2 - (74.0 / 25.0) * LAM**4
S_c2c6 = S_c2 - (24.0 / 5.0) * LAM**6
S_c2c6c8 = S_c2c6 + 8.0 * LAM**8

v.check("lambda^2 exact", LAM**2, 0.04894, rel=1e-3, detail="Expected fail: sin(pi/14)^2 is about 0.049516; 0.04894 is stale.")
v.check("S target", S_TARGET, 0.95987, rel=6e-6)
v.check("LO S", 1.0, 1.0, rel=1e-12)
v.check("LO S gap", 1.0 - S_TARGET, 4.01e-2, rel=2e-3)
v.check("LO relative gap percent", gap_pct_s(1.0), 4.18, rel=3e-3)
v.check(
    "NLO full c2+c4 S",
    S_full_c2c4,
    0.95260,
    rel=2e-4,
    detail="Expected fail: exact c2+c4 with lambda=sin(pi/14) gives about 0.95313.",
)
v.check(
    "NLO full c2+c4 relative gap",
    gap_pct_s(S_full_c2c4),
    -0.758,
    rel=2e-2,
    detail="Expected fail: exact value is about -0.702%, not -0.758%.",
)
v.check("600-cell c2-only S", S_c2, 0.960388, rel=5e-7)
v.check("600-cell c2-only gap", S_c2 - S_TARGET, 5.21e-4, rel=5e-3)
v.check("600-cell c2+c6 S", S_c2c6, 0.959805, rel=2e-7)
v.check("600-cell c2+c6 gap", abs(S_c2c6 - S_TARGET), 6.21e-5, rel=8e-4)
v.check("600-cell c2+c6+c8 S", S_c2c6c8, 0.959853, rel=2e-7)
v.check("600-cell c2+c6+c8 gap", abs(S_c2c6c8 - S_TARGET), 1.40e-5, rel=3e-3)

x = (1.0, 2.0, 3.0)
adj = cross_diag(x, x)
v.record("X cross X equals diagonal cofactor for test X", all(abs(adj[i] - (6.0, 3.0, 2.0)[i]) < 1e-12 for i in range(3)), computed=adj, claimed=(6.0, 3.0, 2.0))
v.record(
    "Freudenthal T(X)=det(X) identity for diagonal test X",
    all(abs(freudenthal_T_diag(x)[i] - det_diag(x)) < 1e-12 for i in range(3)),
    computed=freudenthal_T_diag(x),
    claimed=(det_diag(x), det_diag(x), det_diag(x)),
    detail="Expected fail: the printed T(X)=1/2*(X cross X) cross X is not det(X) times the identity.",
)
unit = (1.0, 1.0, 1.0)
v.record(
    "Freudenthal T(I)=det(I) I",
    all(abs(freudenthal_T_diag(unit)[i] - 1.0) < 1e-12 for i in range(3)),
    computed=freudenthal_T_diag(unit),
    claimed=(1.0, 1.0, 1.0),
    detail="Expected fail: with the paper's 1/2 factor, T(I)=0.5 I.",
)
v.record(
    "c4(theta_W)=0 proof follows from the printed diagonal lemma",
    False,
    computed="the diagonal lemma used to make the Freudenthal shift scalar is false under the displayed cross-product definition",
    claimed="c4(theta_W)=0 proved by Freudenthal sector separation",
    detail="Expected proof fail.",
)

molien_claim = SIN_TARGET * BASE
v.record(
    "finite 2I character average directly yields pi-dependent Molien value",
    False,
    computed=f"claimed sketch includes 3/(8phi)*(1/(1+pi)) = {molien_claim:.12f}; finite-group character sums alone are algebraic and cannot generate the transcendental pi factor",
    claimed="Molien/character sum gives the displayed value",
    detail="Expected proof fail: the pi-dependent LO factor is inserted externally, not produced by 2I character theory.",
)
v.record(
    "2I Clebsch-Gordan weights are fully computed",
    "complete derivation requires fixing the Clebsch--Gordan weights" not in TEX,
    computed="paper explicitly leaves the C_rho weights as an open calculation",
    claimed="600-cell exact limit proved",
    detail="Expected status fail.",
)

u = PHI * LAM**2 / 6.0
f_poly = 1.0 + 6.0 * (-u) + 10.0 * (-u) ** 2 + 5.0 * (-u) ** 3
resummed = 1.0 - (4.0 / 5.0) * LAM**2 * f_poly
v.check(
    "remarked f-polynomial resummation near S target",
    resummed,
    S_TARGET,
    rel=1e-5,
    detail="Expected fail: the displayed resummation gives about 0.96349, not S*=0.95987; the gap is far larger than O(u^4).",
)

c10_shift = -(4.0 / 5.0) * LAM**10
needed_c10_coeff = -(S_c2c6c8 - S_TARGET) / LAM**10
v.check("c10 predicted shift magnitude is tiny", abs(c10_shift), 2.38e-7, rel=2e-3)
v.check("c10 coefficient needed to close exact residual", needed_c10_coeff, 47.0, rel=2e-3)

v.check(
    "master table all-orders deviation vs PDG 0.23122",
    100.0 * (SIN_TARGET - 0.23122) / 0.23122,
    0.0,
    abs_tol=0.02,
    detail="Expected fail: 3/(8phi)=0.2317627 is about +0.235% above 0.23122, not 0%.",
)
v.record(
    "P105-1 is fully proved rather than conditional",
    "conditional on" not in TEX and "Open (OP4" not in TEX,
    computed="paper labels the result conditional on the 2I Clebsch-Gordan calculation and full F4-covariant c4 proof",
    claimed="Proof of Conjecture P105-1",
    detail="Expected status fail.",
)

sys.exit(v.summary())
