"""Riemann zero re-verification, v2 (fallback if the findroot version stalls).

Same scan and bisection as riemann_zeros.py, but:
- checkpoints the bisected t values to data/riemann_scan.json after the scan,
  so a restart never loses the scan;
- replaces mpmath findroot with a single Newton step from the bisected
  value: s1 = s0 - zeta(s0)/zeta'(s0), with zeta'(s0) from mpmath's
  derivative argument. The bisected t is already accurate to ~1e-25, so
  one Newton step lands on the zero to full precision, and the real part
  of s1 is the reported real part. The solver is still free to move off
  the line: s1.real is whatever the Newton step gives.
"""
import hashlib, json, time
from pathlib import Path
from mpmath import mp, mpf, mpc, siegelz, zeta, pi, log

mp.dps = 30
TARGET = 1000
STEP = mpf('0.05')
DATA = Path(__file__).resolve().parent.parent / "data"


def scan():
    zeros = []
    t = mpf('0.1')
    prev_z = siegelz(t)
    prev_t = t
    while len(zeros) < TARGET:
        t = prev_t + STEP
        z = siegelz(t)
        if prev_z == 0:
            zeros.append(prev_t)
        elif (prev_z < 0 < z) or (z < 0 < prev_z):
            a, b = prev_t, t
            za = prev_z
            for _ in range(80):
                m = (a + b) / 2
                zm = siegelz(m)
                if za * zm <= 0:
                    b = m
                else:
                    a, za = m, zm
            zeros.append((a + b) / 2)
        prev_t, prev_z = t, z
    return zeros


def main():
    started = time.time()
    ckpt = DATA / "riemann_scan.json"
    if ckpt.exists():
        zeros = [mpf(x) for x in json.loads(ckpt.read_text())["t_values"]]
        print(f"loaded {len(zeros)} bisected t values from checkpoint")
    else:
        zeros = scan()
        ckpt.write_text(json.dumps({"t_values": [mp.nstr(t, 25) for t in zeros]}))
        print(f"scan done, {len(zeros)} zeros, checkpoint written")
    scan_seconds = time.time() - started

    results = []
    max_re_dev = mpf('0')
    max_abs_zeta = mpf('0')
    worst_i = -1
    for i, tn in enumerate(zeros):
        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

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

    out = {
        "run": "riemann-zero-verification",
        "date": "2026-11-20",
        "method": "Riemann-Siegel Z scan step 0.05 plus one Newton step per zero (zeta and zeta prime, mpmath), dps 30",
        "zeros_checked": TARGET,
        "t_first": mp.nstr(zeros[0], 25),
        "t_last": mp.nstr(zeros[-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": round(scan_seconds, 2),
        "total_seconds": round(total_seconds, 2),
        "zeros": results,
    }
    p = DATA / "riemann_zeros.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()
