#!/usr/bin/env python3
"""
verify_P057.py -- Addendum 57: Yukawa hierarchy from the Cabibbo angle.

This verifier checks the sine/Cabibbo arithmetic and audits the Jordan/Peirce
proof chain in 57_Addendum_YukawaFromCabibbo.tex.  The numerical predictions
y1=sin(pi/14), y2=sin(2pi/14), y3=1, and y2/y1=2cos(pi/14) all reproduce.
The flagged issues are proof-status problems: the advertised Jordan-doubling
theorem is disproved inside its own proof, the Jordan-square normalization is
off by a factor of two, the Peirce double-grading assigns x12 the wrong
E22-eigenvalue, and the step k2=2 closure still depends on physical/ordering
identifications rather than a fully algebraic exclusion of k=3,...,6.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

import numpy as np

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


class ModernVerifier(Verifier):
    """Local adapter: modern check-line output format. Tolerance logic is
    inherited unchanged from verify_common.Verifier; only printing differs.
    Computed/claimed values stay as indented info lines."""

    def __init__(self, name: str) -> None:
        self.name = name
        self.results = []
        print(name)

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        status = "PASS" if ok else "FAIL"
        desc = f"{label} -- {detail}" if detail else label
        print(f"  [{status}] {len(self.results):>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"          computed: {computed}")
            print(f"          claimed : {claimed}")
        return ok

    def summary(self) -> int:
        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("P057 -- Yukawa Hierarchy from Cabibbo")

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

PI = math.pi
H_G2 = 6
DIM_G2 = 14
IM_O_DIM = 7
THETA_C = PI / 14.0
PDG_VUS = 0.22431

y1 = math.sin(THETA_C)
y2 = math.sin(2.0 * THETA_C)
y3 = math.sin(7.0 * THETA_C)


def deg(x: float) -> float:
    return math.degrees(x)


def pct(value: float, target: float) -> float:
    return 100.0 * (value - target) / abs(target)


def diag(i: int) -> np.ndarray:
    m = np.zeros((3, 3))
    m[i, i] = 1.0
    return m


def offdiag(i: int, j: int) -> np.ndarray:
    m = np.zeros((3, 3))
    m[i, j] = 1.0
    m[j, i] = 1.0
    return m


def jordan(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    return 0.5 * (a @ b + b @ a)


def coeff(a: np.ndarray, basis: np.ndarray) -> float:
    denom = float(np.sum(basis * basis))
    return float(np.sum(a * basis) / denom)


v.check("Coxeter number h_G2", H_G2, 6, rel=1e-12)
v.check("dimension identity dim G2=2(h+1)", DIM_G2, 2 * (H_G2 + 1), rel=1e-12)
v.check("dimension identity dim G2=2|ImO|", DIM_G2, 2 * IM_O_DIM, rel=1e-12)
v.check("Cabibbo angle degrees", deg(THETA_C), 12.857, rel=3e-5)
v.check("pi/theta_C denominator", PI / THETA_C, 14, rel=1e-12)

v.check("y1=sin(pi/14)", y1, 0.22252, rel=5e-5)
v.check("y2=sin(2pi/14)", y2, 0.43388, rel=1e-5)
v.check("y3=sin(7pi/14)", y3, 1.0, rel=1e-12)
v.check("Vus residual percent", pct(y1, PDG_VUS), -0.80, rel=5e-3)
v.check("y2/y1", y2 / y1, 1.9498, rel=4e-5)
v.check("double-angle ratio", y2 / y1, 2.0 * math.cos(THETA_C), rel=1e-12)
v.check("double-angle value", 2.0 * y1 * math.cos(THETA_C), y2, rel=1e-12)

e11, e22, e33 = diag(0), diag(1), diag(2)
e12, e13, e23 = offdiag(0, 1), offdiag(0, 2), offdiag(1, 2)

prod_12_23 = jordan(e12, e23)
v.check("Jordan product E12 o E23 gives E13 coefficient", coeff(prod_12_23, e13), 0.5, rel=1e-12)
v.check("doubling map 2(E12 o E23) gives E13 coefficient", coeff(2.0 * prod_12_23, e13), 1.0, rel=1e-12)

square_12 = jordan(e12, e12)
v.check("Jordan square E12^2 coefficient on E11", coeff(square_12, e11), 1.0, rel=1e-12)
v.check("Jordan square E12^2 coefficient on E22", coeff(square_12, e22), 1.0, rel=1e-12)
v.check(
    "paper's Jordan square normalization 1/2(E11+E22)",
    coeff(square_12, e11),
    0.5,
    rel=1e-12,
    detail="Expected fail: for a unit off-diagonal Hermitian block, A o A = A^2 has diagonal coefficients 1, not 1/2.",
)

v.record(
    "Jordan e7-mediated composition derives y2=sin(2theta)",
    False,
    computed="the proof computes Im(u12*e7) perpendicular to e7, hence overlap 0",
    claimed=f"overlap y2 = {y2:.12f}",
    detail="Expected proof-audit fail: the paper itself concludes this route would give y2=0.",
)
v.check(
    "real-unit mediator derives y2 rather than y1",
    y1,
    y2,
    rel=1e-6,
    detail="Expected fail: E23(e0) preserves the u12 direction and gives y1, not y2.",
)
v.record(
    "Theorem y2-from-doubling is proved as advertised",
    "A different approach is required" not in TEX and "fundamental obstruction" not in TEX,
    computed="body states the Jordan route loses direction information and a different approach is required",
    claimed="abstract/status: y2 follows from Jordan triple product / Peirce doubling",
    detail="Expected internal-status fail.",
)

v.check("E33 Peirce eigenvalue of x12", coeff(jordan(e33, e12), e12), 0.0, rel=1e-12)
v.check("E33 Peirce eigenvalue of x13", coeff(jordan(e33, e13), e13), 0.5, rel=1e-12)
v.check("E33 Peirce eigenvalue of x23", coeff(jordan(e33, e23), e23), 0.5, rel=1e-12)
v.check("E22 Peirce eigenvalue of x13", coeff(jordan(e22, e13), e13), 0.0, rel=1e-12)
v.check("E22 Peirce eigenvalue of x23", coeff(jordan(e22, e23), e23), 0.5, rel=1e-12)
v.check(
    "paper's claim x12 is Peirce-0 with respect to E22",
    coeff(jordan(e22, e12), e12),
    0.0,
    rel=1e-12,
    detail="Expected fail: x12 has Peirce eigenvalue 1/2 with respect to E22.",
)

v.record(
    "Peirce grading alone algebraically excludes k2=3,4,5,6",
    False,
    computed="the proof chooses the next unoccupied Weyl step by a monotonicity/minimality argument",
    claimed="Peirce double-grading forces k2=2 uniquely",
    detail="Expected proof-audit fail: the displayed Peirce eigenvalues give an ordering heuristic, not a calculation ruling out every higher step.",
)
v.record(
    "Cabibbo angle equals y1 as a purely algebraic theorem",
    "not a theorem derivable from $G_2$ algebra alone" not in TEX,
    computed="paper states this bridge requires the physical input that CKM mixing arises from off-diagonal angle geometry",
    claimed="not a postulate / theorem from structure alone",
    detail="Expected status fail: P57 itself classifies this as a structural physical identification.",
)
v.record(
    "generation labelling is derivable from G2 alone",
    "additional physical input" not in TEX,
    computed="paper says x12/gen-1, x13/gen-2, x23/gen-3 is an additional physical input",
    claimed="fully structural generation assignment",
    detail="Expected status fail.",
)
v.record(
    "PMNS compatibility is closed here",
    "PMNS mixing angle" not in TEX,
    computed="PMNS/Yukawa joint compatibility remains in the open list",
    claimed="all four moduli fixed with no free parameters",
    detail="Expected status fail.",
)
v.record(
    "precise SU(3) singlet VEV-overlap projection is closed here",
    "precise form of the VEV-overlap formula as an $\\mathrm{SU}(3)$" not in TEX,
    computed="singlet-projection formulation remains in the open list",
    claimed="VEV-overlap formula fully specified",
    detail="Expected status fail.",
)

v.record(
    "Phase 5a-ii is unconditionally closed",
    False,
    computed="numeric sine hierarchy passes, but closure depends on physical CKM-y1 identification, generation labelling, and a Peirce-ordering minimality step",
    claimed="Phase 5a-ii is closed",
    detail="Expected status fail: best read is conditional closure, not an unconditional algebraic theorem.",
)

sys.exit(v.summary())
