#!/usr/bin/env python3
"""Replay all interval images at 512 bits; no seed or zero oracle is called.
Uses the same Arb backend and known factorization, not independent mathematics.
Accepts the full JSON or its byte-identical gzip publication copy.
"""
from pathlib import Path
from fractions import Fraction as F
import json,gzip,time,hashlib
from flint import arb,acb,ctx
from order_contour import aa,cc,text,ztext,image_box,integer
from order_zeta import PRIMES,xi,order_values,inherited_complement,local_complement,central_leading
R=Path(__file__).resolve().parent
REPLAY_STATS={'subdivisions':0,'accepted_leaves':0}

def replay(records,image,bounds):
 x0,x1,y0,y1=map(F,bounds);start=(x0,y0);prev=start;lengths=[F(0)]*4;totals={};cache={}
 def at(p):
  if p not in cache:cache[p]=image(cc(p))
  return cache[p]
 def piece(a,b,values=None,depth=0):
  if values is None:values=image(image_box(a,b))
  safe=all(v.is_finite() and not v.contains(0) for v in values.values())
  if safe:
   va,vb=at(a),at(b);ratios={n:vb[n]/va[n] for n in values}
   safe=all(v.real>0 for v in ratios.values())
  if safe:
   REPLAY_STATS['accepted_leaves']+=1
   return {n:v.arg() for n,v in ratios.items()}
  # Higher precision can change the analytic interval extension (e.g. more
  # Euler--Maclaurin terms), not monotonically shrink it. Subdivide and
  # validate the entire original segment; never waive a failed exclusion.
  if depth>=22:raise AssertionError('replay subdivision exhausted')
  REPLAY_STATS['subdivisions']+=1
  mid=tuple((a[j]+b[j])/2 for j in range(2));left=piece(a,mid,depth=depth+1);right=piece(mid,b,depth=depth+1)
  return {n:left[n]+right[n] for n in left}
 for i,r in enumerate(records):
  a=tuple(map(F,r['start']));b=tuple(map(F,r['end']));assert a==prev
  assert x0<=a[0]<=x1 and x0<=b[0]<=x1 and y0<=a[1]<=y1 and y0<=b[1]<=y1
  if a[1]==b[1]==y0 and b[0]>a[0]:edge=0
  elif a[0]==b[0]==x1 and b[1]>a[1]:edge=1
  elif a[1]==b[1]==y1 and b[0]<a[0]:edge=2
  elif a[0]==b[0]==x0 and b[1]<a[1]:edge=3
  else:raise AssertionError('not a positively oriented rectangular boundary segment')
  lengths[edge]+=abs(b[0]-a[0])+abs(b[1]-a[1])
  vals=image(image_box(a,b))
  for n,v in vals.items():
   if v.is_finite():
    stored=acb(arb(r['images'][n]['real']),arb(r['images'][n]['imag']));assert stored.overlaps(v)
  increments=piece(a,b,vals)
  for n,inc in increments.items():
   assert arb(r['increments'][n]).overlaps(inc)
   totals[n]=totals.get(n,arb(0))+inc
  prev=b
  if (i+1)%5000==0:print('replayed',i+1,flush=True)
 assert prev==start and lengths==[x1-x0,y1-y0,x1-x0,y1-y0]
 return {n:v/(2*arb.pi()) for n,v in totals.items()}

def run():
 ctx.prec=512;REPLAY_STATS.update(subdivisions=0,accepted_leaves=0);start=time.monotonic();p=R/'order-off-axis-results.json'
 raw=p.read_bytes() if p.exists() else gzip.decompress(p.with_suffix('.json.gz').read_bytes());d=json.loads(raw)
 for n,h in d['sources'].items():assert hashlib.sha256((R/n).read_bytes()).hexdigest()==h,n
 # Fail-closed geometric negative control before expensive replay.
 bad=[dict(d['ordinary']['segments'][0],start=['0','0'])]
 try:replay(bad,lambda s:{'ordinary':xi(s)},d['ordinary']['rectangle'])
 except AssertionError:pass
 else:raise AssertionError('tampered geometry was not rejected')
 ordinary=replay(d['ordinary']['segments'],lambda s:{'ordinary':xi(s)},d['ordinary']['rectangle'])
 total=integer(ordinary['ordinary']);assert total==d['ordinary']['total_count']==2*len(d['ordinary']['roots'])==26
 prev=F(0)
 for r in d['ordinary']['roots']:
  lo,hi=F(r['lower']),F(r['upper']);assert prev<lo<hi<60 and hi-lo==F(2,10**20);prev=hi
  a,b=xi(acb(aa(F(1,2)),aa(lo))),xi(acb(aa(F(1,2)),aa(hi)))
  assert a.imag.contains(0) and b.imag.contains(0) and a.real*b.real<0
 assert xi(acb(aa(F(1,2)))).real>0
 checks=d['inherited_complement_checks'];assert len(checks)==78
 seen=set()
 for r in checks:
  key=(r['D'],r['index'],r['family']);assert key not in seen;seen.add(key)
  root=d['ordinary']['roots'][r['index']-1];lo,hi=F(root['lower'])/2,F(root['upper'])/2
  re=F(1,4) if r['family']=='quarter' else F(3,4)
  assert F(r['real'])==re and F(r['height_lower'])==lo and F(r['height_upper'])==hi
  s=acb(aa(re),arb(aa((lo+hi)/2),aa((hi-lo)/2).upper()));v=inherited_complement(s,r['family'],PRIMES[r['D']])
  assert v.is_finite() and not v.contains(0)
 assert seen=={(D,n,f) for D in PRIMES for n in range(1,14) for f in ('quarter','three_quarters')}
 local_counts={};heights=[];local_checks=0
 for p in (2,3,5):
  r=d['local'][str(p)];m=r['count'];q=30*arb(p).log()/arb.pi();assert q>m and q<m+1
  assert arb.pi()*(m+1)/arb(p).log()>30;assert len(r['roots'])==m;local_counts[p]=m
  for k,row in enumerate(r['roots'],1):
   assert row['k']==k;h=arb.pi()*k/arb(p).log();assert h>0 and h<30;heights.append(h)
   assert arb(row['height']).overlaps(h);s=acb(aa(F(1,2)),h)
   assert set(row['complements'])=={str(D) for D,ps in PRIMES.items() if p in ps}
   for D,ps in PRIMES.items():
    if p not in ps:continue
    v=local_complement(s,p,ps);assert v.is_finite() and not v.contains(0);local_checks+=1
   assert 2*arb(p).log()>0
 for i,a in enumerate(heights):
  for b in heights[i+1:]:assert not (a-b).contains(0)
 orders=replay(d['orders']['segments'],order_values,d['orders']['rectangle']);count={n:integer(v) for n,v in orders.items()}
 assert count==d['orders']['total_counts']=={'2':64,'3':72,'30':116}
 for D,ps in PRIMES.items():
  central=len(ps)-1;positive=total+sum(local_counts[p] for p in ps)
  assert central==d['orders']['central_orders'][str(D)] and positive==d['orders']['positive_counts'][str(D)]
  assert count[str(D)]==2*positive+central and central_leading(ps)<0
 out=dict(status='PASS [project] every full segment replayed with Arb at higher precision; same trusted backend',precision_bits=ctx.prec,certificate_sha256=hashlib.sha256(raw).hexdigest(),verifier_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),ordinary_segments=len(d['ordinary']['segments']),order_segments=len(d['orders']['segments']),ordinary_winding={n:text(v) for n,v in ordinary.items()},order_windings={n:text(v) for n,v in orders.items()},ordinary_simple_positive_zeros=13,inherited_complement_checks=len(checks),distinct_local_heights=len(heights),local_complement_checks=local_checks,positive_counts=d['orders']['positive_counts'],central_orders=d['orders']['central_orders'],tampered_geometry_rejected=True,replay_subdivision_stats=dict(REPLAY_STATS),elapsed_seconds=time.monotonic()-start)
 (R/'order-off-axis-verification.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2),flush=True)
if __name__=='__main__':run()
