"""Exact Euler-factor cancellations; explicit obstruction to the usual completion.
Inherited ordinates are transported from existing project Hardy/Turing certificates."""
from pathlib import Path
from fractions import Fraction
import json, hashlib, math
import sympy as sp
import numpy as np
import mpmath as mp
R=Path(__file__).resolve().parent; H=R.parent
x=sp.Symbol('x'); mp.mp.dps=60
C={'G':[1,1,7,7,14,14,28,8,16],'S1':[1,2,15,35,14,14],'R':[1,0,3],'E8':[1]}
q={k:sum(c*x**j for j,c in enumerate(cs)) for k,cs in C.items()}
assert sp.expand(q['G']-(2*x*x)**4*q['G'].subs(x,1/(2*x)))==0
out={'status':'exact polynomial identities and finite-certificate transport; ordinary floats for plotted polynomial roots',
     'window':{'sigma':[-.6,2],'t':[0,30]},'orders':{},'inherited':[],'sources':[]}
for first in (1,33,65,97):
    f=H/f'order-height/zeros/{first:07d}.json'
    out['sources'].append({'file':str(f),'sha256':hashlib.sha256(f.read_bytes()).hexdigest()})
    d=json.loads(f.read_text())
    for row in d['rows']:
        lo,hi=Fraction(row['lower'])/8,Fraction(row['upper'])/8
        if hi<=30:
            out['inherited'].append({'index':row['index'],'sigma':1/16,'t':float((lo+hi)/2),'lower':str(lo),'upper':str(hi)})
out['inherited'].sort(key=lambda a:a['index'])
assert [a['index'] for a in out['inherited']]==list(range(1,len(out['inherited'])+1))
assert out['inherited'][-1]['t']<30
assert int(mp.nzeros(240))==len(out['inherited'])
out['inherited_count']=len(out['inherited'])
out['independent_numerical_N240_check']=int(mp.nzeros(240))
out['turing_source']='order-height/turing-600.json; earlier complete ordinary-zero certificate, not a new count'
period=2*math.pi/math.log(2)
for key,Q in q.items():
    if key=='E8': F=1/(1-x**8)
    else: F=Q/(1-x**4)
    D=sp.cancel((1-x**8)*F)
    assert sp.denom(D)==1
    coeff=[int(sp.expand(D).coeff(x,j)) for j in range(sp.degree(D,x)+1)]
    if key!='E8': assert sp.expand(D-Q*(1+x**4))==0
    alpha=2**(-sp.Rational(1,8))
    degree=int(sp.degree(D,x))
    reflected=sp.Poly(sum(sp.expand(D).coeff(x,k)*alpha**k*x**(degree-k) for k in range(degree+1)),x,extension=alpha)
    inherited_line_gcd=sp.gcd(sp.Poly(D,x,extension=alpha),reflected)
    assert inherited_line_gcd.as_expr()==1
    roots=[]
    if key!='E8':
        independent=mp.polyroots(list(reversed(C[key])),maxsteps=500)
        assert max(min(abs(complex(v)-w) for w in np.roots(C[key][::-1])) for v in independent)<1e-10
    for z in np.roots(C[key][::-1]):
        sigma=-math.log(abs(z))/math.log(2); phase=(-np.angle(z)/math.log(2))%period
        for n in range(-1,5):
            t=phase+n*period
            if 1e-8<t<=30: roots.append({'sigma':sigma,'t':t,'family':'2-local'})
    bridge=[] if key=='E8' else [{'sigma':0.,'t':(2*n+1)*math.pi/(4*math.log(2)),'family':'Euler replacement'} for n in range(14) if (2*n+1)*math.pi/(4*math.log(2))<=30]
    # The reflected bridge zero has 2*x^8=1 and degree 8 (reciprocal Eisenstein).
    witness_nonzero=key=='E8' or sp.gcd(Q,2*x**8-1)==1
    assert witness_nonzero
    assert sp.gcd(sp.diff(D,x),D)==1
    if key=='E8': reflection=None
    else:
        d=sp.degree(D,x); ad=coeff[-1]
        # First nonzero coefficient pair forces A^k; consistency forces (A^k)^d = ad^(-2k).
        k=next(k for k in range(1,d) if coeff[k] and coeff[d-k])
        Ak=sp.Rational(coeff[d-k],ad*coeff[k])
        consistent=sp.simplify(Ak**d-sp.Rational(1,ad**(2*k)))==0
        assert not consistent
        reflection={'degree':int(d),'k':k,'forced_A_to_k':str(Ak),'required_A_to_d':str(sp.Rational(1,ad**2)),'exists':False}
    # independent finite numerical checks of the cancelled formula, away from poles
    rel=[]
    for s in (mp.mpc('.2','.7'),mp.mpc('.9','3.1'),mp.mpc('-.4','2.4')):
        z=mp.power(2,-s)
        qv=sum(mp.mpf(c)*z**j for j,c in enumerate(C[key]))
        fv=1/(1-z**8) if key=='E8' else qv/(1-z**4)
        dv=sum(mp.mpf(c)*z**j for j,c in enumerate(coeff))
        a=mp.zeta(8*s)*(1-z**8)*fv; b=mp.zeta(8*s)*dv
        rel.append(float(abs(a-b)/max(1,abs(b))))
    assert max(rel)<1e-50
    out['orders'][key]={'extra_coefficients':coeff,'extra_polynomial_degree':len(coeff)-1,'local_denominator_cancelled':True,
       'finite_poles':[.125],'usual_completion_symmetric':key=='E8','halfline_zeros_per_period':4 if key=='G' else 0,
       'local_zeros':sorted(roots,key=lambda a:(a['t'],a['sigma'])),'replacement_zeros':bridge,
       'positive_t_extra_zero_count':len(roots)+len(bridge),'polynomial_reflection_test':reflection,
       'numerical_identity_relative_errors':rel,'reflected_bridge_Q_gcd':'1' if key!='E8' else 'not applicable','extra_root_gcd_at_sigma_1_over_16':'1'}
out['trivial_zeros_in_window']=[-.25,-.5]
out['all_trivial_zeros']='s=-k/4, k=1,2,...; simple, since D(2^(k/4)) is positive'
out['bridge_zero_count_to_30']=len(out['orders']['G']['replacement_zeros'])
(R/'results.json').write_text(json.dumps(out,indent=2)+'\n')
print('Inherited zeros through t=30:',len(out['inherited']))
for k,v in out['orders'].items(): print(k,'D coefficients',v['extra_coefficients'],'2-local / replacement zeros',len(v['local_zeros']),len(v['replacement_zeros']),'usual FE',v['usual_completion_symmetric'])
print('Exact Euler cancellations, polynomial reflection obstructions, and 60-digit value checks PASS')
