#!/usr/bin/env python3
"""Independent checker: rational counterexample to the lower inequality
c_n ||A||_{H^4} <= ||A||_{H^1_*} of Kovalev's Conjecture 6.1 (real n x n, n > 2).

Exact integer / rational arithmetic only.  Mathematical argument (re-derived by
the checker's author, see notes.md):

  Z standard Gaussian in R^n, G = Gamma((n+1)/2)/Gamma(n/2), m_n = E|Z| = sqrt(2) G.
  (a) ||A||_{H^4}^4 = W/(n(n+2)),  W = (tr M)^2 + 2 tr(M^2),  M = A^T A.
  (b) c_n = (2/n) / (||P_2||_{H^1} ||P_2||_{H^4}) = 2^{5/4} G (n+2)^{1/4} / (sqrt(pi) n^{3/4}),
      so c_n ||A||_{H^4} = 2^{5/4} G W^{1/4} / (sqrt(pi) n).
  (c) B = diag(1, r, ..., r), g_i = E[b_i Z_i^2/|BZ|].  For every C,
      E|CZ| >= sum_i g_i |C_ii|.  Hence if A = diag(a_i), 0 <= a_i <= t g_i, then
      ||A||_{H^1_*} <= t m_n / n.
  (d) for k = n-1 even, h = k/2, q = 1-r^2:
      g_0 = sqrt(2/pi) I_u,  g_i = sqrt(2/pi) r I_v (i >= 1),
      I_u = int_0^1 (1-x^2)^h (1-q x^2)^(-h) dx,  I_v = int_0^1 (1-x^2)^h (1-q x^2)^(-h-1) dx.
  With t = sqrt(pi/2): ||A||_{H^1_*} <= sqrt(pi) G / n, and the violation
  c_n ||A||_{H^4} > ||A||_{H^1_*} follows from 32 W > pi^4.
"""
import sys
import json
import re
from fractions import Fraction

MAX_STEPS = 5_000_000
RAT = re.compile(r"^[+-]?\d{1,400}(/\d{1,400})?$")


def fail(msg):
    print("REJECTED: " + msg)
    sys.exit(1)


def parse_rat(s, what):
    if isinstance(s, bool) or not isinstance(s, (str, int)):
        fail(f"{what}: not a rational string")
    if isinstance(s, int):
        return Fraction(s)
    s = s.strip()
    if not RAT.match(s):
        fail(f"{what}: bad rational literal {s!r}")
    if "/" in s:
        p, q = s.split("/")
        if int(q) == 0:
            fail(f"{what}: zero denominator")
        return Fraction(int(p), int(q))
    return Fraction(int(s))


def pi_upper():
    """Rational P > pi via Machin: pi = 16 atan(1/5) - 4 atan(1/239)."""
    def atan_inv(x, terms):
        # partial sum of alternating series with `terms` terms
        s = Fraction(0)
        for i in range(terms):
            s += Fraction((-1) ** i, (2 * i + 1) * x ** (2 * i + 1))
        return s
    up5 = atan_inv(5, 41)      # odd number of terms -> upper bound
    lo239 = atan_inv(239, 20)  # even number of terms -> lower bound
    P = 16 * up5 - 4 * lo239
    # sanity: must be within a crude known enclosure of pi
    if not (Fraction(314159265358979, 10 ** 14) < P < Fraction(314159265358980, 10 ** 14)):
        fail("internal: pi bound out of range")
    return P


def main():
    if len(sys.argv) != 2:
        fail("usage: checker.py certificate.json")
    try:
        with open(sys.argv[1]) as f:
            cert = json.load(f)
    except Exception as e:
        fail(f"cannot read certificate: {e}")
    if not isinstance(cert, dict):
        fail("certificate is not an object")

    n = cert.get("n")
    if isinstance(n, bool) or not isinstance(n, int):
        fail("n is not an integer")
    if n <= 2:
        fail("statement requires n > 2")
    if n > 200:
        fail("n too large for this checker")
    k = n - 1
    if k % 2:
        fail("checker's integral formula needs n odd")
    h = k // 2

    rows = cert.get("A")
    if not isinstance(rows, list) or len(rows) != n:
        fail("A does not have n rows")
    A = []
    for i, row in enumerate(rows):
        if not isinstance(row, list) or len(row) != n:
            fail(f"row {i} of A does not have n entries")
        A.append([parse_rat(x, f"A[{i}]") for x in row])

    # --- A must be diagonal with nonnegative entries (hypothesis of step (c)) ---
    for i in range(n):
        for j in range(n):
            if i != j and A[i][j] != 0:
                fail("A is not diagonal")
        if A[i][i] < 0:
            fail("negative diagonal entry")
    if all(A[i][i] == 0 for i in range(n)):
        fail("A is zero")

    # --- W = (tr M)^2 + 2 tr(M^2), M = A^T A, from the full matrix ---
    M = [[sum(A[l][i] * A[l][j] for l in range(n)) for j in range(n)] for i in range(n)]
    trM = sum(M[i][i] for i in range(n))
    trM2 = sum(M[i][j] * M[j][i] for i in range(n) for j in range(n))
    W = trM * trM + 2 * trM2

    # --- witness ---
    r = parse_rat(cert.get("witness_r"), "witness_r")
    if not (0 < r < 1):
        fail("witness_r not in (0,1)")
    N = cert.get("riemann_steps")
    if isinstance(N, bool) or not isinstance(N, int) or N < 1:
        fail("riemann_steps not a positive integer")
    if N > MAX_STEPS:
        fail("riemann_steps too large")
    if r.denominator > 10 ** 6:
        fail("witness_r denominator too large for this checker")

    # --- rigorous lower Riemann sums for I_u, I_v ---
    # q = 1 - r^2 = qn/qd in (0,1).  On [j/N,(j+1)/N]:
    #   (1-x^2)^h   >= ((N^2-(j+1)^2)/N^2)^h           (decreasing, >= 0)
    #   1-q x^2     <= (qd N^2 - qn j^2)/(qd N^2)       (decreasing, > 0)
    # so integrand_u >= (qd*(N^2-(j+1)^2) / (qd N^2 - qn j^2))^h
    #    integrand_v >= that * qd N^2/(qd N^2 - qn j^2)
    q = 1 - r * r
    qn, qd = q.numerator, q.denominator
    if not (0 < qn < qd):
        fail("internal: q out of range")
    S = 10 ** 30  # fixed-point scale; every term is floored
    N2 = N * N
    qdN2 = qd * N2
    su = 0
    sv = 0
    for j in range(N):
        a = N2 - (j + 1) * (j + 1)       # >= 0
        d = qdN2 - qn * j * j            # > 0
        num = (qd * a) ** h
        dh = d ** h
        su += (S * num) // dh
        sv += (S * num * qdN2) // (dh * d)
    Lu = Fraction(su, S * N)   # <= I_u
    Lv = Fraction(sv, S * N)   # <= I_v

    alpha = A[0][0]
    if not (alpha <= Lu):
        fail("A[0][0] exceeds lower bound for I_u")
    for i in range(1, n):
        if not (A[i][i] <= r * Lv):
            fail(f"A[{i}][{i}] exceeds lower bound for r*I_v")

    # --- final inequality 32 W > pi^4 ---
    P = pi_upper()
    if not (32 * W > P ** 4):
        fail("32 W > pi^4 fails")

    print(f"n = {n}, witness r = {r}, steps = {N}")
    print(f"I_u >= {float(Lu):.9f} >= A[0][0] = {float(alpha):.9f}")
    print(f"r*I_v >= {float(r * Lv):.9f} >= max other = {float(max(A[i][i] for i in range(1, n))):.9f}")
    print(f"32W/pi^4 > {float(32 * W / P ** 4):.9f}  (display only)")
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
