#!/usr/bin/env python3
"""verify_P026.py -- Paper 26: BSD geometric framework."""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))

PASS = FAIL = 0
_N = 0


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


class Verifier:
    """Output adapter: identical check semantics, modern [PASS]/[FAIL] format."""

    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_detail = f"abs err={abs(computed - claimed):.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, detail, err_detail)

    def record(self, label, ok, computed="", claimed="", detail="", err_detail=""):
        global _N
        _N += 1
        desc = label + (f" -- {detail}" if detail else "")
        check(_N, desc, ok)
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if err_detail:
            print(f"        {err_detail}")
        return ok

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


v = Verifier("P026 -- Birch and Swinnerton-Dyer")
ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "26_Paper_BSD.tex").read_text()
PI = math.pi
OMEGA = 4 * PI**3 + PI**2 + PI

v.record("TeX source is present", "Birch and Swinnerton-Dyer" in TEX)
v.check("Sato-Tate density normalizes", (2 / PI) * (PI / 2), 1.0, rel=1e-15)
v.check("edge fraction", PI / OMEGA, 0.0229, rel=2e-3)
v.check("boundary fraction", PI**2 / OMEGA, 0.0720, rel=4e-4)
v.check("bulk fraction", 4 * PI**3 / OMEGA, 0.9053, rel=4e-4)
v.record("root number -1 forces central vanishing", True, computed="Lambda(1)= - Lambda(1) implies Lambda(1)=0", claimed="odd analytic rank")
v.record("rank 0/1 known-result boundary is stated", "Gross-Zagier + Kolyvagin" in TEX and "rank 0" in TEX)
v.record("paper disclaims Millennium proof", "not a rigorous proof" in TEX)
v.record("Sato-Tate/global-product scope caveat is present", "global cancellations" in TEX and "marginal distribution" in TEX)

v.record(
    "Sato-Tate layer partition proves BSD rank equality",
    False,
    computed="Sato-Tate is a marginal equidistribution theorem for good-prime Frobenius angles; BSD concerns analytic continuation and vanishing of an infinite Euler product at s=1",
    claimed="three-layer Euler-factor partition supports rank correspondence",
    detail="Expected scope fail.",
)
v.record(
    "higher-rank height formula is available as a proved BSD formula for all E/Q",
    False,
    computed="the r>=2 Beilinson-Bloch/Gross-Zagier-Zhang style input is conjectural/incomplete for general elliptic curves",
    claimed="Height Formula for r_an=r gives L^(r)=C_E R_E",
    detail="Expected proof-status fail.",
)
v.record(
    "derivative-point correspondence proof is valid",
    False,
    computed="the proof assumes the BSD-style formula and then argues consistency of matrix sizes; it does not construct points from zeros or zeros from points",
    claimed="each independent rational point contributes one order of vanishing",
    detail="Expected circularity fail.",
)
v.record(
    "local-global consistency theorem proves zeros iff points",
    False,
    computed="claims about coherent a_p patterns and Kolyvagin descent are heuristic outside analytic rank <=1",
    claimed="zeros at s=1 can only arise from global rational points",
    detail="Expected proof gap.",
)
v.record(
    "BSD formula implies Sha finiteness without assuming BSD",
    False,
    computed="using a formula containing |Sha(E)| as a finite factor already assumes the refined BSD statement/finiteness needed",
    claimed="if rank equality and BSD formula hold then Sha is finite",
    detail="Expected conditional/circular status.",
)
v.record(
    "example y^2=x^3-x+1 has the stated conductor 37 data",
    False,
    computed="the standard conductor-37 rank-one curve is not this short Weierstrass equation as stated; no verification data are supplied",
    claimed="E:y^2=x^3-x+1 has N=37 and rank 1",
    detail="Expected example-data fail.",
)
v.record(
    "Cremona-table BSD verification claim is sourced/reproducible",
    False,
    computed="the TeX cites broad computational verification but gives no table query, dataset version, or script",
    claimed="over 3 million curves verified computationally",
    detail="Expected reproducibility fail.",
)

sys.exit(v.summary())
