#!/usr/bin/env python3
"""[project] Complete interval off-axis zero classification for D=2,3,30, T=30.
Uses ordinary zeta openly: this is factorization transport, NOT an independent
quaternionic L-function, not a new RH test. All accepted contour images are balls.
"""
from pathlib import Path
from fractions import Fraction as F
import json,time,hashlib,importlib.metadata
import mpmath as mp
from flint import arb,acb,ctx
from order_contour import aa,cc,text,ztext,rectangle,path_winding,integer
from order_zeta import PRIMES,xi,order_values,inherited_complement,local_complement,local_factor,central_leading
R=Path(__file__).resolve().parent

def run():
 ctx.prec=384;mp.mp.dps=60;start=time.monotonic()
 out=dict(status='[project] interval-certified finite windows; exact known factorization, no RH progress',coordinate='ideal index [O:I]; reduced-norm coordinate w=2s',precision_bits=ctx.prec,library_versions={n:importlib.metadata.version(n) for n in ('python-flint','mpmath')},sources={n:hashlib.sha256((R/n).read_bytes()).hexdigest() for n in ('order_contour.py','order_zeta.py','order-off-axis.py')})
 def save():
  out['elapsed_seconds']=time.monotonic()-start;(R/'order-off-axis-results.json').write_text(json.dumps(out,indent=2)+'\n')
 print('ordinary xi complete contour to height60',flush=True)
 totals,segments=path_winding(lambda s:{'ordinary':xi(s)},rectangle(F(-1,2),F(3,2),-60,60,step=F(1,2)),progress=lambda n:print('xi segments',n,'seconds',time.monotonic()-start,flush=True))
 winding=totals['ordinary']/(2*arb.pi());count=integer(winding)
 out['ordinary']=dict(rectangle=['-1/2','3/2','-60','60'],winding=text(winding),total_count=count,segments=segments,roots=[])
 print('xi count',count,'accepted segments',len(segments),flush=True);save()
 radius=F(1,10**20)
 for n in range(1,14):
  seed=F(str(mp.im(mp.zetazero(n))));lo,hi=seed-radius,seed+radius
  va,vb=xi(acb(aa(F(1,2)),aa(lo))),xi(acb(aa(F(1,2)),aa(hi)))
  assert va.imag.contains(0) and vb.imag.contains(0) and va.real*vb.real<0
  out['ordinary']['roots'].append(dict(index=n,seed=str(seed),lower=str(lo),upper=str(hi),xi_lower=ztext(va),xi_upper=ztext(vb)))
 assert count==2*len(out['ordinary']['roots'])==26
 out['ordinary']['classification']='13 disjoint real critical-line sign brackets plus conjugates exhaust total26: all simple and on line in this finite window; seeds do not prove completeness'
 out['ordinary']['centre_value']=ztext(xi(acb(aa(F(1,2)))));save()
 print('13 simple critical brackets certified',flush=True)
 checks=[]
 for row in out['ordinary']['roots']:
  lo,hi=F(row['lower']),F(row['upper']);h=(lo+hi)/4;rad=(hi-lo)/4
  for family,re in [('quarter',F(1,4)),('three_quarters',F(3,4))]:
   s=acb(aa(re),arb(aa(h),aa(rad).upper()))
   for D,primes in PRIMES.items():
    v=inherited_complement(s,family,primes);assert v.is_finite() and not v.contains(0)
    checks.append(dict(D=D,index=row['index'],family=family,real=str(re),height_lower=str(lo/2),height_upper=str(hi/2),complement=ztext(v),modulus=text(abs(v))))
 out['inherited_complement_checks']=checks
 out['local']={}
 all_heights=[]
 for p in (2,3,5):
  q=30*arb(p).log()/arb.pi();m=int(float(q.mid()));assert q>m and q<m+1
  row=dict(count=m,cutoff_ratio=text(q),next_height=text(arb.pi()*(m+1)/arb(p).log()),roots=[])
  for k in range(1,m+1):
   height=arb.pi()*k/arb(p).log();assert height>0 and height<30
   all_heights.append(height);s=acb(aa(F(1,2)),height);complements={}
   for D,primes in PRIMES.items():
    if p not in primes:continue
    v=local_complement(s,p,primes);assert v.is_finite() and not v.contains(0)
    complements[str(D)]=ztext(v)
   own=local_factor(s,p);assert own.contains(0)
   row['roots'].append(dict(k=k,height=text(height),own_factor=ztext(own),derivative=text(2*arb(p).log()),complements=complements))
  out['local'][str(p)]=row
 for i,a in enumerate(all_heights):
  for b in all_heights[i+1:]:assert not (a-b).contains(0)
 print('78 inherited complements and 31 distinct local heights certified',flush=True);save()
 print('direct quaternion-order contours to height30',flush=True)
 totals,segments=path_winding(order_values,rectangle(F(1,8),F(7,8),-30,30,step=F(1,2)),progress=lambda n:print('order segments',n,'seconds',time.monotonic()-start,flush=True))
 windings={n:totals[n]/(2*arb.pi()) for n in totals};counts={n:integer(v) for n,v in windings.items()};central={str(D):len(primes)-1 for D,primes in PRIMES.items()}
 positive={str(D):26+sum(out['local'][str(p)]['count'] for p in primes) for D,primes in PRIMES.items()}
 assert all(counts[str(D)]==2*positive[str(D)]+central[str(D)] for D in PRIMES)
 out['orders']=dict(rectangle=['1/8','7/8','-30','30'],windings={n:text(v) for n,v in windings.items()},total_counts=counts,positive_counts=positive,central_orders=central,central_leading={str(D):text(central_leading(primes)) for D,primes in PRIMES.items()},segments=segments,analyticity='centre is removable of order r-1 by exact Laurent expansion; only pole s=1 is outside; no negative real trivial zeros inside')
 out['scope']='Complete NONREAL zeros in the full plane with 0<Im(s)<=30 follow from complete ordinary xi count to60 and exact factorization. Direct order contour is an additional same-factor computational check, not an independent field method. No literal Turing averaged argument is implemented.'
 save();print('PASS positive counts',positive,'total counts',counts,'central',central,'seconds',time.monotonic()-start,flush=True)
if __name__=='__main__':run()
