"""Riemann zero re-verification, round 2 (v3 method, 2,000 zeros).

Same pipeline as compute/riemann_verify.py:
1. LOCATION (PARI/GP 2.19.1, C): lfunzeros on the Riemann zeta
   L-function. The first 1,000 zeros are reused from round 1
   (data/riemann_t.txt, interval [0, 1420], 44.46 s scan); the upper
   zeros come from a second scan on [1420, 2560]
   (data/riemann_t_r2_upper.txt, compute/riemann_scan_r2_upper.gp).
   The full [0, 2560] scan was tried first and killed: it overflowed
   the default 8 MB PARI stack, and with a 256 MB stack it ran past
   377 s while sibling round-2 jobs saturated the machine, so the
   interval was split instead. The first 2,000 t values of the
   combined list are verified here.
2. REAL-PART CHECK (mpmath, Python, dps 30): for each PARI t value, one
   Newton step from s0 = 0.5 + i t using zeta and zeta prime. The step is
   free to move off the line; the reported real part is what it gives.
   Also records |zeta(0.5 + i t)| per zero.
3. COUNT CHECK: number of zeros found vs the Riemann-von Mangoldt count
   N(T) at T = t_2000. A missed off-line zero would show as a mismatch.

Run: ./pari/bin/gp -q < compute/riemann_scan_r2_upper.gp > data/riemann_t_r2_upper.txt
     (first 1,000 t values already in data/riemann_t.txt from round 1)
     then python3 compute/riemann_verify_r2.py
"""
import hashlib, json, time
from pathlib import Path
from mpmath import mp, mpf, mpc, zeta, pi, log

mp.dps = 30
DATA = Path(__file__).resolve().parent.parent / "data"
N_TARGET = 2000
SCAN_R1_SECONDS = 44.46


def main():
    started = time.time()
    lower_lines = (DATA / "riemann_t.txt").read_text().split()
    lower_count = int(lower_lines[0])
    lower = [mpf(x) for x in lower_lines[1:]]
    assert len(lower) == lower_count == 1000, "round-1 file must hold 1,000 zeros"
    upper_lines = (DATA / "riemann_t_r2_upper.txt").read_text().split()
    upper_count = int(upper_lines[0])
    upper = [mpf(x) for x in upper_lines[1:]]
    assert len(upper) == upper_count, f"count line {upper_count} != values {len(upper)}"
    assert upper[0] > lower[-1], "upper scan must continue above the round-1 last zero"
    assert lower_count + upper_count >= N_TARGET, (
        f"combined {lower_count + upper_count} zeros, need {N_TARGET}")
    t_values = (lower + upper)[:N_TARGET]

    results = []
    max_re_dev = mpf('0')
    max_abs_zeta = mpf('0')
    worst_i = -1
    for i, tn in enumerate(t_values):
        s0 = mpc(mpf('0.5'), tn)
        s1 = s0 - zeta(s0) / zeta(s0, derivative=1)
        re_dev = abs(s1.real - mpf('0.5'))
        az = abs(zeta(s0))
        if re_dev > max_re_dev:
            max_re_dev, worst_i = re_dev, i
        if az > max_abs_zeta:
            max_abs_zeta = az
        results.append({
            "n": i + 1,
            "t_bisect": mp.nstr(tn, 25),
            "re": mp.nstr(s1.real, 25),
            "im": mp.nstr(s1.imag, 25),
            "re_deviation": mp.nstr(re_dev, 5),
            "abs_zeta_at_line": mp.nstr(az, 5),
        })
    total_seconds = time.time() - started

    scan_file = DATA / "riemann_scan_r2_upper_seconds.txt"
    scan_seconds = float(scan_file.read_text().strip()) if scan_file.exists() else None

    T = t_values[-1]
    expected = (T / (2 * pi)) * log(T / (2 * pi)) - T / (2 * pi) + mpf('0.875')
    s_of_T = N_TARGET - float(expected)

    out = {
        "run": "riemann-zero-verification-r2",
        "date": "2026-11-20",
        "method": "Location: PARI/GP 2.19.1 lfunzeros on the Riemann zeta L-function, realprecision 30. First 1,000 zeros reused from round 1 (interval [0, 1420]); zeros 1,001-2,000 from a second scan on [1420, 2560]. Real-part check: one mpmath Newton step per zero from 0.5 + i t using zeta and zeta prime, dps 30, free to move off the line.",
        "zeros_checked": N_TARGET,
        "t_first": mp.nstr(t_values[0], 25),
        "t_last": mp.nstr(t_values[-1], 25),
        "max_re_deviation": mp.nstr(max_re_dev, 5),
        "worst_zero_n": worst_i + 1,
        "max_abs_zeta_at_line": mp.nstr(max_abs_zeta, 5),
        "von_mangoldt_expected_at_T": float(expected),
        "S_of_T": s_of_T,
        "scan_seconds": scan_seconds,
        "scan_seconds_round1_reused": SCAN_R1_SECONDS,
        "total_seconds": round(total_seconds, 2),
        "zeros": results,
    }
    p = DATA / "riemann_zeros_r2.json"
    p.write_text(json.dumps(out, indent=2))
    print(json.dumps({k: v for k, v in out.items() if k != "zeros"}, indent=2))
    print("results_sha256:", hashlib.sha256(p.read_bytes()).hexdigest())


if __name__ == "__main__":
    main()
