#!/usr/bin/env python3
"""2kwas independent recheck of iis:2611.00285 (Periodic cancellation in finite sums of
reciprocal Fibonacci powers). Written from the paper's statements only; it does not import
or reuse the authors' verify.py. Exact integer/rational arithmetic throughout.

Checks
  A  the worked example a=15, m=5, k=1 (factor 150 = 30 from the lcm, then 5 from the sum)
  B  Theorem 1: D(a)*G(a) = P(a), G(a) = gcd(P,E), G(a) | M = C^(m+1), C = lcm(F_1..F_m)^k,
     and C equals the Lean form lcm(F_1^k..F_m^k); the moving-block lcm identity (FibDen.window)
  C  periodicity: the least period t* of G seen in the data divides the Pisano period pi(M),
     and G(a + pi(M)) = G(a) directly whenever pi(M) is small enough to compute G beyond it
  D  Theorem 2: lcm(D_n, L_{n//2}^k) = L_n^k, and its corollary for small primes
  E  the rational denominator lemma on random signed rationals
  F  the Binet asymptotic: (D(a) 5^{k(m+1)/2} G(a) / phi^{k((m+1)a+m(m+1)/2)} - 1) * phi^{2a} stays bounded
"""
import random, sys, time
from fractions import Fraction
from math import gcd, lcm, prod

T0 = time.time()
NF = 4000
F = [0, 1]
while len(F) < NF:
    F.append(F[-1] + F[-2])

def lcm_list(xs):
    out = 1
    for x in xs:
        out = lcm(out, x)
    return out

def window_data(a, m, k):
    d = [F[a + j] ** k for j in range(m + 1)]
    P = prod(d)
    S = sum((Fraction(1, x) for x in d), Fraction(0))
    D = S.denominator
    E = sum(P // x for x in d)
    return d, P, D, E

def C_of(m, k):
    return lcm_list(F[1:m + 1]) ** k

fails = []
def check(cond, msg):
    if not cond:
        fails.append(msg)
        print("FAIL:", msg)

# ---------- A: the worked example
d, P, D, E = window_data(15, 5, 1)
L = lcm_list(d)
print(f"A  a=15,m=5,k=1: F_15..F_20 = {d}")
print(f"   P/lcm = {P // L}, lcm/D = {L // D}, G = P/D = {P // D}")
check(P % L == 0 and P // L == 30 and L % D == 0 and L // D == 5 and P // D == 150, "example 150/30/5")

# ---------- B: Theorem 1 and the window identity
KMAX, MMAX, AMAX = 6, 10, 300
nwin = 0
maxratio = {}
for k in range(1, KMAX + 1):
    for m in range(0, MMAX + 1):
        C = C_of(m, k)
        C_lean = lcm_list([F[i] ** k for i in range(1, m + 1)])
        check(C == C_lean, f"C paper != C lean at m={m},k={k}")
        M = C ** (m + 1)
        for a in range(1, AMAX + 1):
            d, P, D, E = window_data(a, m, k)
            nwin += 1
            check(P % D == 0, f"D does not divide P at {(a,m,k)}")
            G = P // D
            check(G == gcd(P, E), f"G != gcd(P,E) at {(a,m,k)}")
            check(M % G == 0, f"G does not divide M at {(a,m,k)}")
            check(lcm(D, C) == lcm(lcm_list(d), C), f"window lcm identity fails at {(a,m,k)}")
print(f"B  Theorem 1 + window identity: {nwin} windows (k<= {KMAX}, m<= {MMAX}, a<= {AMAX}), failures so far: {len(fails)}")

# ---------- C: periodicity
def pisano_iter(n):
    if n == 1:
        return 1
    a, b, t = 0, 1, 0
    while True:
        a, b = b, (a + b) % n
        t += 1
        if a == 0 and b == 1:
            return t

def factor_small(n):
    out, p = {}, 2
    while p * p <= n:
        while n % p == 0:
            out[p] = out.get(p, 0) + 1
            n //= p
        p += 1
    if n > 1:
        out[n] = out.get(n, 0) + 1
    return out

def pisano(M_factors):
    t = 1
    for p, e in M_factors.items():
        pp = pisano_iter(p)
        pp2 = pisano_iter(p * p)
        assert pp2 == p * pp, (p, pp, pp2)  # no Wall-Sun-Sun prime among these small p
        t = lcm(t, p ** (e - 1) * pp)
    return t

def G_seq(m, k, amax):
    out = [None]
    for a in range(1, amax + 1):
        d, P, D, E = window_data(a, m, k)
        out.append(P // D)
    return out

def least_period(g, amax):
    for t in range(1, amax // 3 + 1):
        if all(g[a + t] == g[a] for a in range(1, amax - t + 1)):
            return t
    return None

print("C  periodicity (t* = least period of G seen in exact data, pi(M) = Pisano period of M)")
print("   m k   M-factorization          pi(M)                t*     pi(M)/t*      direct G(a+pi(M))=G(a)")
inconclusive = []
for m in range(0, 9):
    for k in (1, 2, 3):
        base = factor_small(lcm_list(F[1:m + 1])) if m >= 1 else {}
        Mf = {p: e * k * (m + 1) for p, e in base.items()}
        M = prod(p ** e for p, e in Mf.items())
        piM = pisano(Mf) if Mf else 1
        t = None
        for amax in (900, 3000):
            g = G_seq(m, k, amax)
            check(all(M % x == 0 for x in g[1:]), f"G does not divide M somewhere in a<={amax}, m={m},k={k}")
            t = least_period(g, amax)
            if t is not None:
                break
        if t is None:
            inconclusive.append((m, k))
        else:
            check(piM % t == 0, f"t*={t} does not divide pi(M)={piM} for m={m},k={k}")
        direct = "-"
        if piM + 200 <= NF - m - 1 and piM <= 1500:
            gg = G_seq(m, k, piM + 200)
            ok = all(gg[a + piM] == gg[a] for a in range(1, 201))
            check(ok, f"G(a+pi(M)) != G(a) for m={m},k={k}")
            direct = "yes, a=1..200" if ok else "NO"
        fs = "*".join(f"{p}^{e}" for p, e in sorted(Mf.items())) or "1"
        ts = str(t) if t else f">{amax // 3}"
        rs = str(piM // t) if t else "-"
        pis = str(piM) if piM < 10**18 else f"{piM:.3e}"
        print(f"   {m} {k}   {fs:24s} {pis:>20s} {ts:>6s} {rs:>12s}      {direct}")
print(f"   least period not reached within a<=3000 (inconclusive, not a failure): {inconclusive}")

# ---------- D: Theorem 2 (prefixes)
NMAX = 400
small_primes = [p for p in range(2, 200) if all(p % q for q in range(2, int(p ** 0.5) + 1))]
def vp(n, p):
    v = 0
    while n % p == 0:
        n //= p
        v += 1
    return v
npre = 0
for k in range(1, KMAX + 1):
    S = Fraction(0)
    Ls = [1]
    for n in range(1, NMAX + 1):
        Ls.append(lcm(Ls[-1], F[n]))
    for n in range(1, NMAX + 1):
        S += Fraction(1, F[n] ** k)
        Dn = S.denominator
        npre += 1
        check(lcm(Dn, Ls[n // 2] ** k) == Ls[n] ** k, f"Theorem 2 fails at n={n},k={k}")
        if k <= 2 and n <= 200:
            for p in small_primes:
                if vp(Ls[n], p) > vp(Ls[n // 2], p):
                    check(vp(Dn, p) == k * vp(Ls[n], p), f"corollary fails at n={n},k={k},p={p}")
print(f"D  Theorem 2: {npre} prefixes (k<= {KMAX}, n<= {NMAX}); corollary checked for p<200, k<=2, n<=200")

# ---------- E: rational lemma on random signed rationals
rng = random.Random(20261128)
primes = [2, 3, 5, 7, 11, 13]
ntests = 0
for _ in range(20000):
    s = rng.randint(1, 6)
    rs = []
    for _ in range(s):
        den = prod(p ** rng.randint(0, 4) for p in primes if rng.random() < 0.5)
        num = rng.randint(-50, 50) or 1
        rs.append(Fraction(num, den))
    ds = [r.denominator for r in rs]
    Bmin = lcm_list([gcd(ds[i], ds[j]) for i in range(s) for j in range(s) if i != j])
    B = Bmin * rng.choice([1, 1, 2, 3, 6])
    Dsum = sum(rs, Fraction(0)).denominator
    for di in ds:
        check(lcm(Dsum, B) % di == 0, f"lemma part 1 fails: {rs}, B={B}")
    check((Dsum * B ** s) % prod(ds) == 0, f"lemma part 2 fails: {rs}, B={B}")
    ntests += 1
print(f"E  rational lemma: {ntests} random signed instances, failures so far: {len(fails)}")

# ---------- F: Binet asymptotic
from decimal import Decimal, getcontext
getcontext().prec = 400
phi = (1 + Decimal(5).sqrt()) / 2
worst = 0
for (m, k) in [(0, 1), (1, 1), (3, 1), (5, 1), (5, 2), (8, 3)]:
    mx = 0
    for a in range(20, 301, 7):
        d, P, D, E = window_data(a, m, k)
        G = P // D
        expo = k * ((m + 1) * a + m * (m + 1) // 2) if (m * (m + 1)) % 2 == 0 else None
        R = Decimal(D) * Decimal(5) ** (Decimal(k * (m + 1)) / 2) * G / phi ** (k * ((m + 1) * a) + Decimal(k * m * (m + 1)) / 2)
        mx = max(mx, abs(R - 1) * phi ** (2 * a))
    print(f"F  m={m},k={k}: max_a |R(a)-1|*phi^(2a) over a=20..300 = {float(mx):.4f}")
    worst = max(worst, mx)
check(worst < 1e6, "asymptotic error not O(phi^-2a)")

print(f"\nTOTAL failures: {len(fails)}   time {time.time() - T0:.1f}s")
sys.exit(1 if fails else 0)
