"""Exact score for the first autocorrelation constant ladder (isitsolved 'autocorrelation').

usage: py -3.15 c1_score.py FILE.json
FILE.json: {"heights": [...]} (nonnegative integers, the ladder certificate)
       or  {"values": ["p/q", ...]} (Atris format, exact rationals)
       or  a JSON list of numbers.
f is the step function with these N heights on N equal steps of [-1/4, 1/4]. f*f is piecewise
linear with knots at the grid, so max(f*f)/(int f)^2 = 2N max_k c_k / S^2 with c = a*a (discrete
autoconvolution) and S = sum a. Computed exactly (Kronecker substitution, gmpy2 big integers).
"""
import json, sys
from fractions import Fraction
import gmpy2

def load(path):
    d = json.load(open(path))
    if isinstance(d, dict) and "heights" in d: v = d["heights"]
    elif isinstance(d, dict) and "values" in d: v = d["values"]
    else: v = d
    fr = [Fraction(x) for x in v]
    den = 1
    for x in fr: den = den * x.denominator // gmpy2.gcd(den, x.denominator)
    return [int(x * den) for x in fr]

def score(a):
    N = len(a); S = sum(a)
    if min(a) < 0: raise ValueError("negative height")
    amax = max(a)
    B = (N * amax * amax).bit_length() + 2
    X = gmpy2.mpz(0)
    for x in reversed(a): X = (X << B) | x          # fine for N up to ~1e6
    Y = X * X
    mask = (gmpy2.mpz(1) << B) - 1
    cmax, kmax = 0, -1
    for k in range(2 * N - 1):
        c = int(Y & mask); Y >>= B
        if c > cmax: cmax, kmax = c, k
    return Fraction(2 * N * cmax, S * S), kmax

if __name__ == "__main__":
    if len(sys.argv) != 2: print(__doc__); sys.exit(1)
    a = load(sys.argv[1]); s, k = score(a)
    print(f"N={len(a)} score={float(s):.15f} (exact {s.numerator.bit_length()}-bit fraction) peak index {k}")
    print("score_20dp", f"{s.numerator * 10**20 // s.denominator}")
