#!/usr/bin/env python3
"""Finite arithmetic companion to 正核的谱质量、迹与截断误差.

Only the Python standard library is required. Exact Fractions compute finite
coefficient sums. Decimal values are illustrative, NOT outward-rounded bounds.
The stated infinite-tail and weighted-loss conclusions are supplied by the
article's proofs; this program does not verify infinite convergence, PSD for all
samples, Mercer, Gaussian laws, or a continuum inequality by sampling.

Usage: python foundations-positive-kernel-trace-certificate.py --n 3 --self-test
"""
import argparse
from decimal import Decimal, localcontext
from fractions import Fraction as F
import json

PI_APPROX = Decimal("3.14159265358979323846264338327950288419716939937510")
MAX_N = 1000


def validate_n(n):
    if isinstance(n, bool) or not isinstance(n, int) or not 0 <= n <= MAX_N:
        raise ValueError(f"n must be an integer in 0..{MAX_N}")


def finite_coefficients(n):
    validate_n(n)
    q2 = sum((F(4, (2*j-1)**2) for j in range(1, n+1)), F(0))
    q4 = sum((F(16, (2*j-1)**4) for j in range(1, n+1)), F(0))
    return q2, q4


def as_decimal(q):
    return Decimal(q.numerator) / Decimal(q.denominator)


def exact_formula(constant, coefficient, pi_power):
    if not coefficient:
        return str(constant)
    return f"{constant} - ({coefficient}) / pi^{pi_power}"


def certificate(n):
    q2, q4 = finite_coefficients(n)
    op_coefficient = F(4, (2*n+1)**2)
    with localcontext() as ctx:
        ctx.prec = 50
        p = PI_APPROX
        trace = Decimal(1)/2 - as_decimal(q2)/p**2
        hs_squared = Decimal(1)/6 - as_decimal(q4)/p**4
        op = as_decimal(op_coefficient)/p**2
        if trace <= 0 or hs_squared <= 0:
            raise ArithmeticError("Decimal precision insufficient for positive tails")
        a = 2*trace
        out = {
            "n": n,
            "scope": "Finite exact rational arithmetic; decimals are illustrations, not rigorous rounding certificates. Infinite claims rely on the article's proofs.",
            "finite_coefficients_exact": {"sum_inverse_half_integers_squared": str(q2), "sum_inverse_half_integers_fourth": str(q4)},
            "tail_formulas_from_proved_identities": {
                "trace_tail_R": exact_formula(F(1, 2), q2, 2),
                "HS_norm_squared_S": exact_formula(F(1, 6), q4, 4),
                "HS_norm": "sqrt(S)",
                "operator_norm_O": f"({op_coefficient}) / pi^2",
                "uniform_kernel_error_upper_bound": "2 R",
            },
            "decimal_illustrations": {"R": str(+trace), "S": str(+hs_squared), "sqrt_S": str(hs_squared.sqrt()), "O": str(+op), "uniform_upper_2R": str(+a), "alpha_1_upper_bound": str(a*(1-a.ln()))},
            "weighted_loss_from_proved_bounds": {
                "alpha_less_than_2_total": "1 / (2-alpha); all finite-rank weighted errors tend to zero",
                "alpha_1_error_upper": "a*(1+log(1/a)), where a=2R; no integration of an infinite constant bound",
                "alpha_at_least_2_error": "+infinity for every finite n",
                "alpha_at_least_2_witness": "r_0(x)=x" if n == 0 else f"r_n(x) >= x/2 on 0 < x <= {F(1, 4*n)}",
                "spectral_coordinates": "Original Lebesgue eigenfunctions; changing loss does not redefine the operator measure",
            },
        }
        if n:
            out["analytic_tail_enclosures"] = {
                "R_lower": f"({F(2, 2*n+1)}) / pi^2",
                "R_upper": f"({F(2, 2*n-1)}) / pi^2",
                "S_lower": f"({F(8, 3*(2*n+1)**3)}) / pi^4",
                "S_upper": f"({F(8, 3*(2*n-1)**3)}) / pi^4",
                "justification": "Monotone integral comparison proved in article, not inferred from finite checks",
            }
        else:
            out["analytic_tail_enclosures"] = {"n_zero": "R=1/2, S=1/6, O=4/pi^2 exactly; N>=1 integral-comparison formula not used"}
    return out


def self_test():
    checks = 0
    def need(condition, label):
        nonlocal checks
        checks += 1
        if not condition:
            raise RuntimeError("Self-test failed: " + label)
    need(finite_coefficients(0) == (F(0), F(0)), "empty sums")
    need(finite_coefficients(1) == (F(4), F(16)), "first Brownian mode")
    need(finite_coefficients(3) == (F(1036,225), F(821296,50625)), "N=3 exact fractions")
    previous = (F(0), F(0))
    for n in range(1, 65):
        current = finite_coefficients(n)
        need(current[0]-previous[0] == F(4, (2*n-1)**2), "finite second-power increment")
        need(current[1]-previous[1] == F(16, (2*n-1)**4), "finite fourth-power increment")
        previous = current
    # Finite rank-one arithmetic, not a general kernel theorem.
    need(F(1,3)**2 == F(1,9), "rank-one HS square")
    for n in (0, 1, 3):
        r = F(1,3) if n == 0 else F(0)
        s = F(1,9) if n == 0 else F(0)
        need(r*r == s, "rank-one termination")
    # Repeated sample points: direct quadratic form equals grouped squares.
    xs, cs = [F(0),F(1,2),F(0),F(1)], [F(2),F(-3),F(-1),F(4)]
    direct = sum((cs[i]*cs[j] for i in range(4) for j in range(4) if xs[i] == xs[j]), F(0))
    grouped = sum((sum((cs[i] for i in range(4) if xs[i] == x),F(0))**2 for x in set(xs)), F(0))
    need(direct == grouped == 26, "diagonal kernel repeated-point quadratic form")
    for bad in (-1, MAX_N+1, 1.5, True):
        try:
            validate_n(bad)
        except ValueError:
            need(True, "invalid input rejected")
        else:
            need(False, "invalid input was accepted")
    for n in (0,1,3,64):
        report = certificate(n)
        need(report["n"] == n, "output retains n")
        need(Decimal(report["decimal_illustrations"]["S"]) > 0, "illustrative HS square positive")
    return {"passed": True, "finite_checks": checks, "boundary": "No finite self-test certifies any infinite-dimensional or probabilistic theorem"}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--n", type=int, default=3, help=f"Number of retained Brownian modes, 0..{MAX_N}")
    parser.add_argument("--self-test", action="store_true", help="Check finite algebra and input handling; no theorem certification")
    args = parser.parse_args()
    try:
        result = certificate(args.n)
        if args.self_test:
            result["self_test"] = self_test()
    except (ValueError, ArithmeticError, RuntimeError) as exc:
        parser.error(str(exc))
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
