#!/usr/bin/env python3
"""
verify_P067.py -- Addendum 67: Bryant Fano origin of CP violation.

This verifier checks the finite Fano-plane incidence claims, Bryant 3-form
components, selected octonion products/associators, calibration numerics, and
the CP-angle conversion in 67_Addendum_BryantFanoCP.tex.

The basic Bryant/Fano combinatorics are sound: the seven lines, the absence of
(1,2,7), the lines through 7, and the (1,2,7) associator all check. The flagged
issues are mostly overstrong uniqueness/equivariance claims and repeated stale
CP-calibration arithmetic: cos(5*pi/28), Phi, and the calibration angle do not
match the printed values; the displayed alpha-to-delta conversion does not
equal 31*pi/84; and nonzero e7 calibrations also occur on the (1,6,7) and
(2,5,7) Fano lines unless additional physical gauge restrictions are imposed.
"""

from __future__ import annotations

import itertools
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("P067 -- Bryant Fano CP")

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

PI = math.pi
LINES = {
    (1, 2, 3): 1,
    (1, 4, 5): 1,
    (1, 6, 7): 1,
    (2, 4, 6): 1,
    (2, 5, 7): -1,
    (3, 4, 7): -1,
    (3, 5, 6): -1,
}


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


def component(i: int, j: int, k: int) -> int:
    """Bryant 3-form component phi_ijk for distinct basis indices."""
    if len({i, j, k}) < 3:
        return 0
    vals = [i, j, k]
    key = tuple(sorted(vals))
    if key not in LINES:
        return 0
    inv = 0
    for a in range(3):
        for b in range(a + 1, 3):
            if vals[a] > vals[b]:
                inv += 1
    return LINES[key] * (-1 if inv % 2 else 1)


def basis_product(i: int, j: int) -> tuple[int, int]:
    """Return sign, k for e_i * e_j = sign * e_k."""
    if i == j:
        return -1, 0
    for (a, b, c), sign in LINES.items():
        if (i, j) == (a, b):
            return sign, c
        if (i, j) == (b, c):
            return sign, a
        if (i, j) == (c, a):
            return sign, b
        if (j, i) == (a, b):
            return -sign, c
        if (j, i) == (b, c):
            return -sign, a
        if (j, i) == (c, a):
            return -sign, b
    raise AssertionError((i, j))


def multiply_basis_terms(term1: tuple[int, int], term2: tuple[int, int]) -> tuple[int, int]:
    s1, i = term1
    s2, j = term2
    if i == 0:
        return s1 * s2, j
    if j == 0:
        return s1 * s2, i
    s3, k = basis_product(i, j)
    return s1 * s2 * s3, k


def calibration(i: int, j: int, k: int) -> int:
    return component(i, j, k)


pairs = list(itertools.combinations(range(1, 8), 2))
pair_counts = {pair: 0 for pair in pairs}
for line in LINES:
    for pair in itertools.combinations(line, 2):
        pair_counts[tuple(sorted(pair))] += 1

lines_through_7 = {line for line in LINES if 7 in line}
lines_through_4 = {line for line in LINES if 4 in line}
lines_with_4_and_7 = {line for line in LINES if 4 in line and 7 in line}

v.check("Fano line count", len(LINES), 7, rel=0)
v.check("Fano pair count", len(pair_counts), 21, rel=0)
v.record(
    "each unordered pair lies on exactly one Fano line",
    all(count == 1 for count in pair_counts.values()),
    computed=pair_counts,
    claimed="21 pairs, each once",
)
v.record("Bryant phi_123", component(1, 2, 3) == 1, component(1, 2, 3), "+1")
v.record("Bryant phi_257", component(2, 5, 7) == -1, component(2, 5, 7), "-1")
v.record("Bryant phi_347", component(3, 4, 7) == -1, component(3, 4, 7), "-1")
v.record("Bryant phi_127 vanishes", component(1, 2, 7) == 0, component(1, 2, 7), "0")
v.record(
    "lines through 7",
    lines_through_7 == {(1, 6, 7), (2, 5, 7), (3, 4, 7)},
    computed=sorted(lines_through_7),
    claimed="{1,6,7}, {2,5,7}, {3,4,7}",
)
v.record(
    "unique line through {4,7}",
    lines_with_4_and_7 == {(3, 4, 7)},
    computed=sorted(lines_with_4_and_7),
    claimed="{3,4,7}",
)
v.record(
    "only line connecting Im(H) to e4",
    False,
    computed=f"lines through e4 are {sorted(lines_through_4)}; all include one of e1,e2,e3 plus e4",
    claimed="only {3,4,7} connects Im(H) to the Cayley-Dickson doubling element e4",
    detail="Expected wording fail: {1,4,5} and {2,4,6} also contain e4 and an Im(H) basis element. The unique true statement is line through both e4 and e7.",
)

e1e2 = basis_product(1, 2)
left = multiply_basis_terms(e1e2, (1, 7))
e2e7 = basis_product(2, 7)
right = multiply_basis_terms((1, 1), e2e7)
v.record("(e1 e2) e7", left == (1, 4), left, "+e4")
v.record("e1 (e2 e7)", right == (-1, 4), right, "-e4")
v.record(
    "associator [e1,e2,e7]",
    left == (1, 4) and right == (-1, 4),
    computed="(+e4) - (-e4) = 2e4",
    claimed="2e4 != 0",
)
v.record("e3 e4 seam relation", basis_product(3, 4) == (-1, 7), basis_product(3, 4), "-e7")

theta_c = PI / 14.0
psi = 5.0 * PI / 28.0
s1 = math.cos(PI / 14.0)
s2 = math.cos(2.0 * PI / 14.0)
cos_psi = math.cos(psi)
phi_cal = -s1 * s2 * cos_psi
alpha = math.acos(phi_cal)
delta_ckm = PI / 3.0 + theta_c / 2.0
delta_from_alpha_formula = (PI - alpha + PI / 3.0 + theta_c / 2.0) % PI

v.check("s1 = cos(pi/14)", s1, 0.9749, rel=3e-5)
v.check("s2 = cos(2pi/14)", s2, 0.9010, rel=4e-5)
v.check(
    "cos(5pi/28)",
    cos_psi,
    0.8526,
    rel=5e-4,
    detail="Expected fail: exact cos(5*pi/28) is about 0.846724.",
)
v.check(
    "calibration Phi = -s1*s2*cos(psi)",
    phi_cal,
    -0.7490,
    rel=5e-4,
    detail="Expected fail: exact product is about -0.743745, matching the stale A66 calibration value.",
)
v.check(
    "calibration angle alpha",
    deg(alpha),
    138.5,
    rel=2e-3,
    detail="Expected fail: exact alpha is about 138.05 degrees.",
)
v.check(
    "alpha approximately pi - pi/3 - thetaC/2",
    deg(alpha),
    deg(PI - PI / 3.0 - theta_c / 2.0),
    rel=5e-3,
    detail="Expected fail: pi - pi/3 - thetaC/2 is about 113.57 degrees, not 138.5 degrees.",
)
v.check("delta_CKM = pi/3 + pi/28", deg(delta_ckm), 66.43, rel=5e-4)
v.check("delta_CP = -delta_CKM", -deg(delta_ckm), -66.43, rel=5e-4)
v.check(
    "displayed alpha-to-delta conversion",
    deg(delta_from_alpha_formula),
    deg(delta_ckm),
    rel=5e-3,
    detail="Expected fail: substituting the displayed alpha gives about 108.38 degrees, not 66.43 degrees.",
)
v.record(
    "quark-sector sign convention is consistent",
    False,
    computed="Theorem states sgn(delta_CKM)=sgn(phi_347)=-1, but the recovery corollary sets delta_CKM=+31*pi/84 and delta_CP=-31*pi/84.",
    claimed="single sign convention for quark/lepton phases",
    detail="Expected internal-consistency fail.",
)

v.record(
    "only (3,4,7) gives nonzero e7 calibration",
    False,
    computed=f"phi(e1,e6,e7)={calibration(1,6,7)}, phi(e2,e5,e7)={calibration(2,5,7)}, phi(e3,e4,e7)={calibration(3,4,7)}",
    claimed="nonzero iff projection onto the (3,4,7) Fano subspace",
    detail="Expected fail: other e7 Fano lines are nonzero unless excluded by additional gauge/physical assumptions.",
)
v.record(
    "G2-equivariant claim preserves the same coordinate Fano line",
    False,
    computed="The scalar phi(u12,u13,e7) is G2-invariant, but the named coordinate line {3,4,7} is basis/gauge data; generic G2 rotations do not merely permute the seven coordinate triples.",
    claimed="the same Fano line contributes in any G2-related gauge",
    detail="Expected equivariance fail.",
)
v.record(
    "KM counting is derived from Fano geometry rather than paralleled by it",
    False,
    computed="The SM count (n-1)(n-2)/2 follows from U(n) rephasing; binomial 3-form counting gives the same n=2,3 zero/one contrast but is not the full U(n) derivation.",
    claimed="KM counting from Fano geometry",
    detail="Expected proof-status fail.",
)
v.record(
    "CP violation requires color as a physical theorem",
    False,
    computed="The restricted calibration with both vectors in Im(H) and third vector e7 vanishes, but identifying this with a model-independent theorem that CP violation requires SU(3)c uses inherited TOE dictionary assumptions.",
    claimed="CP violation requires color",
    detail="Expected status fail: the finite algebraic statement is valid, the physical necessity claim is not proved here.",
)
v.record(
    "OP-P66-5 fully closed",
    False,
    computed="P67 supplies a Fano/Weyl interpretation, but the numeric thetaC/2 and alpha-to-delta bridge remain structural and the conversion formula is arithmetically inconsistent.",
    claimed="OP-P66-5 resolved / Phase 5c complete proved",
    detail="Expected proof-status fail.",
)

sys.exit(v.summary())
