#!/usr/bin/env python3
"""Independently check a compact Goldbach Lab NDJSON pair export."""

from __future__ import annotations

import json
import sys
from pathlib import Path

MR64_BASES = (2, 325, 9375, 28178, 450775, 9780504, 1795265022)
U64 = 1 << 64


def is_prime64(n: int) -> bool:
    """Deterministic Miller-Rabin on the proven range below 2^64."""
    if n < 2 or n >= U64:
        return False
    for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
        if n == p:
            return True
        if n % p == 0:
            return False
    d, s = n - 1, 0
    while d % 2 == 0:
        d //= 2
        s += 1
    for base in MR64_BASES:
        a = base % n
        if a == 0:
            continue
        x = pow(a, d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True


def canonical_integer(row: dict[str, object], key: str, line: int) -> int:
    value = row.get(key)
    if not isinstance(value, str) or not value.isascii() or not value.isdecimal():
        raise ValueError(f"line {line}: {key} must be a decimal string")
    if len(value) > 1 and value.startswith("0"):
        raise ValueError(f"line {line}: {key} is not in canonical decimal form")
    return int(value)


def verify(path: Path) -> int:
    expected = 4
    count = 0
    ecpp_marked = 0
    with path.open("r", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            row = json.loads(line)
            if not isinstance(row, dict):
                raise ValueError(f"line {line_number}: expected a JSON object")
            n = canonical_integer(row, "even_value", line_number)
            p = canonical_integer(row, "prime_p", line_number)
            q = canonical_integer(row, "prime_q", line_number)
            if n != expected or n >= U64 or p > q or p + q != n:
                raise ValueError(f"line {line_number}: skipped, duplicate, or invalid Goldbach pair")
            if row.get("local_check_passed") is not True:
                raise ValueError(f"line {line_number}: local check marker is not true")
            if not is_prime64(p) or not is_prime64(q):
                raise ValueError(f"line {line_number}: independent deterministic primality check failed")
            if not isinstance(row.get("pari_ecpp_replay_passed"), bool):
                raise ValueError(f"line {line_number}: PARI/GP status marker is missing")
            ecpp_marked += int(row["pari_ecpp_replay_passed"])
            expected += 2
            count += 1
            if count % 100_000 == 0:
                print(f"Checked {count:,} rows through {n:,}", flush=True)
    if count == 0:
        raise ValueError("export contains no pair records")
    print(f"PASS: independently checked {count:,} consecutive pairs from 4 through {expected - 2:,}.")
    print(f"Server-reported PARI/GP replay markers: {ecpp_marked:,} of {count:,}.")
    print("The PARI/GP markers are not certificate files; independently recreate certificates for any pair in the Main Lab.")
    print("Finite data verification does not prove Goldbach for all even integers.")
    return 0


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python3 verify_stream.py goldbach-through-N.ndjson")
    try:
        raise SystemExit(verify(Path(sys.argv[1])))
    except (OSError, ValueError, json.JSONDecodeError) as exc:
        print(f"FAIL: {exc}", file=sys.stderr)
        raise SystemExit(1)
