"""2kwas independent exact scorer for iis:2611.00276 (first autocorrelation constant C_1a).

Ratio for a step function with N equal steps on [-1/4, 1/4] and heights a_i >= 0:
    max(f*f) / (int f)^2 = 2N max_k c_k / S^2,   c = a*a (discrete autoconvolution), S = sum a_i.
Method, independent of the authors' Kronecker/gmpy2 scorer: the autoconvolution is computed exactly by a
number-theoretic transform modulo five NTT primes (numpy int64, all products < 2^62) and recombined by CRT.
The CRT modulus (~2^150) exceeds the bound N * max(a)^2, which is asserted. Rational heights (Atris format)
are scaled to integers by the lcm of their denominators first.
usage: python review_score.py FILE.json
"""
import json, sys
from fractions import Fraction
from math import lcm
import numpy as np

PRIMES = [(998244353, 3), (167772161, 3), (469762049, 3), (754974721, 11), (1811939329, 13)]

def ntt(a, p, g, invert=False):
    a = a.copy(); n = len(a)
    j = 0                                        # bit reversal permutation
    rev = np.zeros(n, dtype=np.int64)
    bits = n.bit_length() - 1
    idx = np.arange(n, dtype=np.int64)
    for b in range(bits):
        rev |= ((idx >> b) & 1) << (bits - 1 - b)
    a = a[rev]
    length = 2
    while length <= n:
        w = pow(g, (p - 1) // length, p)
        if invert: w = pow(w, p - 2, p)
        half = length // 2
        ws = np.ones(half, dtype=np.int64)
        for i in range(1, half):                 # powers of w (vectorised by doubling below)
            pass
        ws = np.empty(half, dtype=np.int64); ws[0] = 1
        k = 1
        while k < half:
            step = pow(w, k, p)
            ws[k:2 * k] = (ws[:min(k, half - k)] * step) % p
            k *= 2
        a = a.reshape(-1, length)
        u = a[:, :half].copy()
        v = (a[:, half:] * ws) % p
        a[:, :half] = (u + v) % p
        a[:, half:] = (u - v) % p
        a = a.reshape(-1)
        length *= 2
    if invert:
        a = (a * pow(n, p - 2, p)) % p
    return a

def autoconv_exact(a):
    N = len(a); n = 1
    while n < 2 * N: n *= 2
    M = 1; res = None
    bound = N * max(a) ** 2
    for p, g in PRIMES:
        x = np.zeros(n, dtype=np.int64)
        x[:N] = np.array([v % p for v in a], dtype=np.int64)
        X = ntt(x, p, g)
        y = ntt((X * X) % p, p, g, invert=True)[:2 * N - 1]
        r = [int(v) for v in y]
        if res is None:
            res = r
        else:   # CRT combine res (mod M) with r (mod p)
            inv = pow(M % p, p - 2, p)
            res = [c + M * (((ri - c) % p) * inv % p) for c, ri in zip(res, r)]
        M *= p
    assert M > bound, "CRT modulus too small"
    return res

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

if __name__ == "__main__":
    a = load(sys.argv[1])
    assert min(a) >= 0
    N, S = len(a), sum(a)
    c = autoconv_exact(a)
    # spot check against direct sums at a few indices
    for k in (0, N // 3, N - 1, 2 * N - 2):
        lo, hi = max(0, k - N + 1), min(k, N - 1)
        assert c[k] == sum(a[i] * a[k - i] for i in range(lo, hi + 1)), k
    cmax = max(c); kmax = c.index(cmax)
    r = Fraction(2 * N * cmax, S * S)
    print(f"N={N} zeros={a.count(0)} S={S} peak k={kmax}")
    print("ratio floor 20dp: 1." + str(r.numerator * 10**20 // r.denominator)[1:])
