"""Independent local checks on the archived numbers and external proof records."""
from pathlib import Path
from datetime import datetime, timezone
import csv, re, json, hashlib, math
from decimal import Decimal as D, getcontext
from scipy.integrate import quad
from scipy.special import expi
import numpy as np
root=Path(__file__).resolve().parents[1]; src=root/'sources'; res=root/'results'
def rows(name): return list(csv.DictReader((res/name).open()))
def digest(p): return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
    assets=json.loads((src/'index.json').read_text())
    assert all(digest(src/a['file'])==a['sha256'] for a in assets)
    published={v.split()[-1]:v.split()[0] for v in (src/'SHA256SUMS').read_text().splitlines() if len(v.split())==2}
    verified={n:digest(src/n)==published[n] for n in ('audit.log','con-leche-compare.log','nanoda.log','sandbox-timeline.txt')}
    assert all(verified.values())
    main=(src/'Main.lean').read_text(); audit=(src/'audit.log').read_text(); comp=(src/'con-leche-compare.log').read_text()
    targets=[]
    for name,typ,term in re.findall(r'^theorem (\w+) : (\w+) := (.+)$',main,re.M):
        ax=re.search("'"+name+r"' depends on axioms: \[(.*?)\]",audit).group(1).split(', ')
        c=f"theorem {name} justified by the solution" in comp
        assert c and set(ax)=={'propext','Classical.choice','Quot.sound'}
        targets.append(dict(theorem=name,type=typ,term=term,axioms=ax,comparison=c))
    assert len(targets)==5
    getcontext().prec=55
    rootdiff=max(abs(D(r['height'])-D(r['reference'])) for r in rows('zeros.csv'))
    ref=[(int(n),D(t)) for n,t in map(str.split,(src/'lmfdb.txt').read_text().splitlines())]
    assert [(int(r['index']),D(r['reference'])) for r in rows('zeros.csv')]==ref
    # Different prime-count algorithm: Legendre-like combinatorial sieve over distinct floor(N/i).
    def pi(N):
        vals=sorted({N//i for i in range(1,math.isqrt(N)+1)}|set(range(1,math.isqrt(N)+1)),reverse=True)
        S={v:v-1 for v in vals}
        for p in range(2,math.isqrt(N)+1):
            if S[p]==S[p-1]: continue
            for v in vals:
                if v<p*p: break
                S[v]-=S[v//p]-S[p-1]
        return S[N]
    ptable={int(r['x']):r for r in rows('primes.csv')}
    exact={n:pi(n) for n in (10,100,1000,10000,100000,1000000)}
    assert all(v==int(ptable[n]['pi']) for n,v in exact.items())
    li_cross=max(abs(quad(lambda t:1/math.log(t),2,n)[0]+expi(math.log(2))-float(ptable[n]['li'])) for n in exact)
    assert li_cross<1e-6
    data=dict(utc=datetime.now(timezone.utc).isoformat(),local_source_hashes=len(assets),MIT_log_hash_matches=verified,theorems=targets,principal_target_definition='Mathlib.NumberTheory.LSeries.RiemannZeta.RiemannHypothesis (definition name RiemannHypothesis, global namespace)',max_printed_height_difference=str(rootdiff),independent_prime_counts=exact,li_max_quadrature_difference=li_cross,local_full_kernel_replay=False,external_evidence={"solution_declarations":int(re.search(r'solution.ndjson \((\d+) declarations accepted',comp).group(1)),"nanoda_exit":int(re.search(r'Exit status: (\d+)',(src/'nanoda.log').read_text()).group(1))})
    (res/'audit.json').write_text(json.dumps(data,indent=2))
if __name__=='__main__': main()

