"""Check 1: every nontrivial zero of the Riemann zeta function up to height T lies on the critical line.

Method (the same idea used in the big published verifications, at a much smaller scale):

1. ON the line. Along the critical line s = 1/2 + it, zeta can be written as
       zeta(1/2 + it) = Z(t) * exp(-i*theta(t))
   where Z(t) (the Riemann-Siegel Z function) is a REAL number. So every time Z changes sign,
   zeta has a zero exactly on the line (intermediate value theorem). We look for sign changes
   between Gram points g_n (where theta(g_n) = n*pi), splitting intervals finer when needed.

2. IN the whole strip. Separately we count ALL zeros with 0 < Im(s) < T, wherever they are,
   using the Riemann-von Mangoldt formula
       N(T) = theta(T)/pi + 1 + S(T),   S(T) = arg zeta(1/2 + iT) / pi
   with the argument tracked continuously from 2 + iT to 1/2 + iT. This count doesn't care
   whether zeros are on the line.

3. If (zeros found on the line) == (zeros in the whole strip), then none of the zeros below T
   is off the line. That is what the Riemann Hypothesis predicts. It is evidence, not proof:
   RH is about infinitely many zeros, and this checks finitely many.

Run:  python check1_zeros.py 30000      (checks zeros up to Gram point g_30000)
"""
import sys, json, time, math
from multiprocessing import Pool
import mpmath as mp

mp.mp.dps = 20


def Z(t):
    return float(mp.siegelz(t))


def gram(n):
    return float(mp.grampoint(n))


def chunk_values(rng):
    lo, hi = rng
    out = []
    for n in range(lo, hi):
        g = gram(n)
        out.append((n, g, Z(g)))
    return out


def sign_changes(ts, zs):
    return sum(1 for a, b in zip(zs, zs[1:]) if (a > 0) != (b > 0))


def find_in_interval(a, b, za, zb, need, depth=0):
    """Look for `need` sign changes of Z in (a, b) by evaluating on finer and finer grids."""
    for k in (4, 16, 64, 256):
        ts = [a + (b - a) * i / k for i in range(k + 1)]
        zs = [za] + [Z(t) for t in ts[1:-1]] + [zb]
        c = sign_changes(ts, zs)
        if c >= need:
            return c, k
    return c, k


def verify_block(block):
    """block: list of (n, g, Z) from one good Gram point to the next. Returns zeros found and notes."""
    expected = len(block) - 1
    zs = [z for _, _, z in block]
    found = sign_changes(None, zs) if False else sum(1 for a, b in zip(zs, zs[1:]) if (a > 0) != (b > 0))
    refined = []
    if found < expected:
        found = 0
        for (n1, g1, z1), (n2, g2, z2) in zip(block, block[1:]):
            # each Gram interval in a block should hold one zero on average; search each one finely
            c, k = find_in_interval(g1, g2, z1, z2, 1)
            found += c
            if c != (1 if (z1 > 0) != (z2 > 0) else 0):
                refined.append({"from": g1, "to": g2, "found": c, "grid": k})
        if found < expected:
            # try the whole block at the finest grid
            g1, g2 = block[0][1], block[-1][1]
            c, k = find_in_interval(g1, g2, block[0][2], block[-1][2], expected)
            found = max(found, c)
    return found, expected, refined


def S_of_T(T, steps=4000):
    """S(T) = arg zeta(1/2 + iT)/pi, arg tracked continuously along the segment from 2 + iT to 1/2 + iT.
    On Re(s) = 2, |zeta(s) - 1| < 1, so the argument there is the principal value."""
    prev = mp.zeta(mp.mpc(2, T))
    arg = float(mp.arg(prev))
    sigmas = [2 - 1.5 * i / steps for i in range(1, steps + 1)]
    for s in sigmas:
        cur = mp.zeta(mp.mpc(s, T))
        d = float(mp.arg(cur / prev))  # change in argument between neighbouring points, in (-pi, pi]
        if abs(d) > 1.0:
            raise RuntimeError(f"argument jumped by {d:.2f} at sigma={s:.4f}; use more steps")
        arg += d
        prev = cur
    return arg / math.pi


def N_formula(T):
    theta = float(mp.siegeltheta(T))
    S = S_of_T(T)
    return theta / math.pi + 1 + S, S


def main():
    M = int(sys.argv[1]) if len(sys.argv) > 1 else 3000
    t0 = time.time()
    # Z at Gram points g_-1 .. g_M, in parallel
    edges = list(range(-1, M + 1, 40)) + [M + 1]
    with Pool(10) as p:
        parts = p.map(chunk_values, list(zip(edges, edges[1:])))
    pts = [x for part in parts for x in part]
    good = [(-1) ** (n % 2) * z > 0 for n, g, z in pts]
    bad_gram = sum(1 for x in good if not x)
    # split into Gram blocks: from one good Gram point to the next good one
    idx = [i for i, ok in enumerate(good) if ok]
    blocks = [pts[a:b + 1] for a, b in zip(idx, idx[1:])]
    with Pool(10) as p:
        res = p.map(verify_block, blocks)
    on_line = sum(f for f, e, r in res)
    expected = sum(e for f, e, r in res)
    problem_blocks = [(blocks[i][0][0], blocks[i][-1][0], f, e) for i, (f, e, r) in enumerate(res) if f != e]
    refinements = [x for f, e, r in res for x in r]
    # zeros between 0 and the first good Gram point: g_-1 is about 9.67; the first zero is at 14.13, so none there
    first_good_n = pts[idx[0]][0]
    T_last = pts[idx[-1]][1]
    # count every zero in the strip up to just past the last good Gram point (move off any zero first)
    Ts = T_last + 1e-4
    with mp.workdps(25):
        NT, S = N_formula(Ts)
    lib = int(mp.nzeros(Ts))
    elapsed = time.time() - t0
    out = {
        "gram_points_checked": len(pts), "last_gram_index": pts[idx[-1]][0], "height_T": T_last,
        "zeros_found_on_line": on_line, "expected_from_gram_blocks": expected,
        "N_T_formula": NT, "N_T_rounded": round(NT), "S_T": S, "N_T_mpmath_nzeros": lib,
        "gram_law_failures": bad_gram, "gram_blocks": len(blocks), "longest_block": max(len(b) - 1 for b in blocks),
        "intervals_needing_finer_search": len(refinements), "problem_blocks": problem_blocks,
        "first_good_gram_index": first_good_n, "seconds": round(elapsed, 1),
        "all_on_line": on_line == round(NT) and abs(NT - round(NT)) < 0.05,
    }
    json.dump(out, open(f"check1_result_{M}.json", "w"), indent=1)
    # save Z at Gram points for the page's chart
    json.dump([[n, round(g, 6), round(z, 6)] for n, g, z in pts], open(f"check1_gram_{M}.json", "w"))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
