#!/usr/bin/env python3
"""Independent checker for the claimed counterexample to Conjectures 3 (mainc1) and
7 (lili4) of Lopez Pouso & Segura, arXiv:2305.19128v3.

Usage: python3 checker.py certificate.json

Exact arithmetic only (Python ints / Fractions, elements of Q(sqrt d)); no floats.
Prints VERIFIED as the last line and exits 0 only if the certificate describes the
genuine n-point Gauss-Legendre rule and, at the stated indices,
    x_i/z_i - 1               > pi^2/(12 kappa^2)      (Conjecture 3 upper bound fails)
    alpha_i/(1 - zbar_i^2) - 1 > pi^2/(12 kappa^2)      (Conjecture 7 upper bound fails)
Anything else: exit 1 with a reason.
"""
import json
import re
import sys
from fractions import Fraction

MAX_N = 60
MAX_DIGITS = 2000
INT_RE = re.compile(r"-?(0|[1-9][0-9]*)\Z")


class Fail(Exception):
    pass


def need(cond, msg):
    if not cond:
        raise Fail(msg)


# ---------------------------------------------------------------- Q(sqrt d)
class Q:
    """a + b*sqrt(D), a, b rational, D a fixed squarefree integer >= 2."""
    D = None
    __slots__ = ("a", "b")

    def __init__(self, a, b=0):
        self.a = Fraction(a)
        self.b = Fraction(b)

    @staticmethod
    def lift(o):
        if isinstance(o, Q):
            return o
        if isinstance(o, (int, Fraction)) and not isinstance(o, bool):
            return Q(o, 0)
        raise TypeError("bad operand %r" % (o,))

    def __add__(self, o):
        o = Q.lift(o)
        return Q(self.a + o.a, self.b + o.b)
    __radd__ = __add__

    def __neg__(self):
        return Q(-self.a, -self.b)

    def __sub__(self, o):
        return self + (-Q.lift(o))

    def __rsub__(self, o):
        return Q.lift(o) + (-self)

    def __mul__(self, o):
        o = Q.lift(o)
        return Q(self.a * o.a + Q.D * self.b * o.b, self.a * o.b + self.b * o.a)
    __rmul__ = __mul__

    def inv(self):
        norm = self.a * self.a - Q.D * self.b * self.b
        # D squarefree >= 2  =>  norm == 0 iff a == b == 0
        if norm == 0:
            raise Fail("division by zero in Q(sqrt(d))")
        return Q(self.a / norm, -self.b / norm)

    def __truediv__(self, o):
        return self * Q.lift(o).inv()

    def __pow__(self, k):
        r = Q(1)
        for _ in range(k):
            r = r * self
        return r

    def is_zero(self):
        return self.a == 0 and self.b == 0

    def sign(self):
        """Exact sign of a + b*sqrt(D), decided by rational comparisons."""
        a, b = self.a, self.b
        sa = (a > 0) - (a < 0)
        sb = (b > 0) - (b < 0)
        if sb == 0:
            return sa
        if sa == 0:
            return sb
        if sa == sb:
            return sa
        # opposite signs: |a| vs |b| sqrt(D)  <=>  a^2 vs b^2 D  (never equal, D squarefree)
        lhs, rhs = a * a, b * b * Q.D
        need(lhs != rhs, "internal: a^2 == d b^2 with d squarefree")
        return sa if lhs > rhs else sb

    def __eq__(self, o):
        o = Q.lift(o)
        return self.a == o.a and self.b == o.b

    def __hash__(self):
        return hash((self.a, self.b))

    def __repr__(self):
        return "(%s + %s*sqrt(%d))" % (self.a, self.b, Q.D)


def gt(x, y):
    return (Q.lift(x) - Q.lift(y)).sign() > 0


# ---------------------------------------------------------------- parsing
def no_float(s):
    raise Fail("floating-point literal %r in certificate" % (s,))


def no_const(s):
    raise Fail("non-finite constant %r in certificate" % (s,))


def no_dups(pairs):
    d = {}
    for k, v in pairs:
        need(k not in d, "duplicate key %r in certificate" % (k,))
        d[k] = v
    return d


def is_int(v):
    return isinstance(v, int) and not isinstance(v, bool)


def parse_int_str(s, what):
    need(isinstance(s, str), "%s: expected decimal-integer string, got %r" % (what, s))
    need(len(s) <= MAX_DIGITS, "%s: integer string too long" % what)
    need(INT_RE.match(s) is not None, "%s: not a decimal integer string: %r" % (what, s))
    return int(s)


def parse_rat(v, what):
    need(isinstance(v, list) and len(v) == 2, "%s: rational must be [num, den]" % what)
    num = parse_int_str(v[0], what + " numerator")
    den = parse_int_str(v[1], what + " denominator")
    need(den > 0, "%s: denominator must be positive" % what)
    return Fraction(num, den)


def parse_num(v, what):
    need(isinstance(v, list) and len(v) == 2, "%s: number must be a pair [a, b]" % what)
    return Q(parse_rat(v[0], what + ".a"), parse_rat(v[1], what + ".b"))


def squarefree(d):
    p = 2
    while p * p <= d:
        if d % (p * p) == 0:
            return False
        p += 1
    return True


# ---------------------------------------------------------------- mathematics
def legendre(n):
    """Coefficient list (low degree first) of P_n via Bonnet:
    (k+1) P_{k+1} = (2k+1) x P_k - k P_{k-1}."""
    p0 = [Fraction(1)]
    if n == 0:
        return p0
    p1 = [Fraction(0), Fraction(1)]
    for k in range(1, n):
        nxt = [Fraction(0)] * (k + 2)
        for j, c in enumerate(p1):
            nxt[j + 1] += (2 * k + 1) * c
        for j, c in enumerate(p0):
            nxt[j] -= k * c
        nxt = [c / (k + 1) for c in nxt]
        p0, p1 = p1, nxt
    return p1


def peval(coeffs, x):
    r = Q(0)
    for c in reversed(coeffs):
        r = r * x + c
    return r


def pi_bounds(terms=12):
    """Rational L < pi < U from Machin: pi = 16 atan(1/5) - 4 atan(1/239).
    atan(1/q) = sum_{k>=0} (-1)^k / ((2k+1) q^(2k+1)) is alternating with strictly
    decreasing terms, so a partial sum ending on a + term is a strict upper bound and
    one ending on a - term is a strict lower bound."""
    def atan_inv(q, m):  # sum of first m terms
        s = Fraction(0)
        for k in range(m):
            t = Fraction(1, (2 * k + 1) * q ** (2 * k + 1))
            s += t if k % 2 == 0 else -t
        return s
    need(terms % 2 == 0, "internal")
    a5_lo, a5_hi = atan_inv(5, terms), atan_inv(5, terms + 1)
    a239_lo, a239_hi = atan_inv(239, terms), atan_inv(239, terms + 1)
    need(a5_lo < a5_hi and a239_lo < a239_hi, "internal: arctan enclosure inverted")
    L = 16 * a5_lo - 4 * a239_hi
    U = 16 * a5_hi - 4 * a239_lo
    # independent sanity anchors: 3.14159265 < pi < 3.14159266 (and Archimedes 223/71, 22/7)
    need(Fraction(223, 71) < L < U < Fraction(22, 7), "pi enclosure fails Archimedes sanity check")
    need(Fraction(314159265, 10 ** 8) < L and U < Fraction(314159266, 10 ** 8),
         "pi enclosure not tight / wrong")
    return L, U


def check(path):
    with open(path, "r", encoding="utf-8") as f:
        raw = f.read()
    need(len(raw) <= 5_000_000, "certificate too large")
    try:
        cert = json.loads(raw, parse_float=no_float, parse_constant=no_const,
                          object_pairs_hook=no_dups)
    except Fail:
        raise
    except Exception as e:
        raise Fail("certificate is not valid JSON: %s" % e)
    need(isinstance(cert, dict), "certificate must be a JSON object")
    required = {"n", "d", "nodes", "weights", "conjecture3_index", "conjecture7_index"}
    allowed = required | {"statement"}
    need(required <= set(cert), "missing fields: %s" % sorted(required - set(cert)))
    need(set(cert) <= allowed, "unknown fields: %s" % sorted(set(cert) - allowed))

    n, d = cert["n"], cert["d"]
    need(is_int(n) and 1 <= n <= MAX_N, "n must be an integer in 1..%d" % MAX_N)
    need(is_int(d) and 2 <= d <= 10 ** 12, "d must be an integer >= 2 (and <= 10^12)")
    need(squarefree(d), "d = %d is not squarefree" % d)
    Q.D = d

    need(isinstance(cert["nodes"], list) and len(cert["nodes"]) == n, "nodes must be a list of n numbers")
    need(isinstance(cert["weights"], list) and len(cert["weights"]) == n, "weights must be a list of n numbers")
    x = [parse_num(v, "nodes[%d]" % (i + 1)) for i, v in enumerate(cert["nodes"])]
    w = [parse_num(v, "weights[%d]" % (i + 1)) for i, v in enumerate(cert["weights"])]

    i3, i7 = cert["conjecture3_index"], cert["conjecture7_index"]
    need(is_int(i3) and 1 <= i3 <= n, "conjecture3_index must be an integer in 1..n")
    need(is_int(i7) and 1 <= i7 <= n - 1, "conjecture7_index must be an interior index in 1..n-1")

    # --- 1. the nodes are exactly the zeros of P_n, in increasing order
    P = legendre(n)
    need(len(P) == n + 1 and P[n] != 0, "internal: P_n has wrong degree")
    need(peval(P, Q(1)) == Q(1), "internal: P_n(1) != 1")
    for i in range(n - 1):
        need(gt(x[i + 1], x[i]), "nodes not strictly increasing at position %d" % (i + 1))
    for i in range(n):
        need(peval(P, x[i]).is_zero(), "nodes[%d] is not a zero of P_%d" % (i + 1, n))
    # n distinct zeros of a degree-n polynomial: these are all the zeros of P_n.
    print("nodes: %d distinct zeros of P_%d, strictly increasing -> the Gauss-Legendre nodes" % (n, n))

    # --- 2. the weights are the Gauss-Legendre weights
    # (a) exactness on x^k, k = 0..2n-1 (k = 0..n-1 already determines w uniquely: Vandermonde)
    for k in range(2 * n):
        s = Q(0)
        for i in range(n):
            s = s + w[i] * (x[i] ** k)
        target = Fraction(2, k + 1) if k % 2 == 0 else Fraction(0)
        need(s == Q(target), "rule not exact on x^%d" % k)
    # (b) independent cross-check: w_i = 2 / ((1 - x_i^2) P_n'(x_i)^2)
    dP = [j * P[j] for j in range(1, n + 1)]
    for i in range(n):
        dv = peval(dP, x[i])
        need(not dv.is_zero(), "internal: repeated root")
        need(w[i] == Q(2) / ((Q(1) - x[i] * x[i]) * dv * dv),
             "weights[%d] disagrees with 2/((1-x^2)P_n'(x)^2)" % (i + 1))
        need(w[i].sign() > 0, "weights[%d] not positive" % (i + 1))
    need(sum(w, Q(0)) == Q(2), "weights do not sum to 2")
    print("weights: exact for degree <= %d and match the closed formula -> the Gauss-Legendre weights" % (2 * n - 1))

    # --- 3. quantities from statement.md
    kappa = Fraction(2 * n + 1, 2)
    zbar = [Q(-1)]
    for i in range(1, n + 1):
        zbar.append(zbar[i - 1] + w[i - 1])           # zbar_i = zbar_{i-1} + w_i
    need(zbar[n] == Q(1), "zbar_n != 1")
    for i in range(1, n + 1):                           # closed form  -1 + sum_{j<=i} w_j
        need(zbar[i] == Q(-1) + sum(w[:i], Q(0)), "zbar recurrence/closed form mismatch")
    z = [None] + [(zbar[i - 1] + zbar[i]) / 2 for i in range(1, n + 1)]
    alpha = [Q(0)]
    for i in range(1, n + 1):
        alpha.append(alpha[i - 1] - 2 * x[i - 1] * w[i - 1])   # alpha_i = alpha_{i-1} - 2 x_i w_i
    for i in range(0, n + 1):                           # alpha_i = 2 sum_{k=i+1}^n x_k w_k
        s = Q(0)
        for k in range(i + 1, n + 1):
            s = s + x[k - 1] * w[k - 1]
        need(alpha[i] == 2 * s, "alpha_%d: the two definitions disagree" % i)

    # --- 4. rigorous rational upper bound for pi^2/(12 kappa^2)
    L, U = pi_bounds()
    B = U * U / (12 * kappa * kappa)                    # B > pi^2/(12 kappa^2) since 0 < pi < U
    print("kappa = %s; using rational B > pi^2/(12 kappa^2)" % kappa)

    # --- 5. the two violations
    need(z[i3].sign() > 0, "z_%d is not positive (Conjecture 3 ratio must be taken at a positive node)" % i3)
    need(x[i3 - 1].sign() > 0, "x_%d is not positive" % i3)
    lhs3 = x[i3 - 1] / z[i3] - 1
    need(gt(lhs3, B), "Conjecture 3 upper bound is NOT violated at i=%d: x_i/z_i - 1 = %r" % (i3, lhs3))
    print("Conjecture 3: x_%d/z_%d - 1 = %r > B > pi^2/(12 kappa^2)" % (i3, i3, lhs3))

    den7 = Q(1) - zbar[i7] * zbar[i7]
    need(den7.sign() > 0, "1 - zbar_%d^2 is not positive" % i7)
    lhs7 = alpha[i7] / den7 - 1
    need(gt(lhs7, B), "Conjecture 7 upper bound is NOT violated at i=%d: alpha_i/(1-zbar_i^2) - 1 = %r" % (i7, lhs7))
    print("Conjecture 7: alpha_%d/(1 - zbar_%d^2) - 1 = %r > B > pi^2/(12 kappa^2)" % (i7, i7, lhs7))

    print("Both strict upper bounds fail for the %d-point Gauss-Legendre rule: "
          "Conjectures 3 and 7 are false as stated (for all n)." % n)


def main(argv):
    if len(argv) != 2:
        print("usage: python3 checker.py certificate.json")
        return 1
    try:
        check(argv[1])
    except Fail as e:
        print("REJECTED: %s" % e)
        return 1
    except Exception as e:  # any unexpected error is a rejection
        print("REJECTED: unexpected error: %s: %s" % (type(e).__name__, e))
        return 1
    print("VERIFIED")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
