"""Exact ideal counts and a distinct signed zero-sensitive diagnostic. Grant pt199u."""
from pathlib import Path
from math import isqrt,log
from fractions import Fraction
import json,random,hashlib,math
import numpy as np
import mpmath as mp
R=Path(__file__).resolve().parent;H=R.parent
Q={'G':[1,1,7,7,14,14,28,8,16],'S1':[1,2,15,35,14,14],'R':[1,0,3],'E8':[1]}
def correction(q):
 c=q+[0]*4
 for j,a in enumerate(q):c[j+4]+=a
 return c
corrections={k:correction(q) if k!='E8' else [1] for k,q in Q.items()}
def root8(n):return isqrt(isqrt(isqrt(n)))
def binary_root8(n):
 if n<1:return 0
 lo,hi=0,1<<((n.bit_length()+7)//8)
 while lo+1<hi:
  mid=(lo+hi)//2
  if mid**8<=n:lo=mid
  else:hi=mid
 return lo
def f2(kind,k):
 if kind=='E8':return int(k%8==0)
 return sum(a for j,a in enumerate(Q[kind]) if k>=j and (k-j)%4==0)
def raw_count(kind,x):return sum(c*root8(x>>j) for j,c in enumerate(corrections[kind]))
def odd_count(kind,x):return sum(f2(kind,k)*((binary_root8(x>>k)+1)//2) for k in range(x.bit_length()))
def local_coefficients(c,n):
 b=[0]*(n+1)
 for k in range(1,n+1):b[k]=(k*c[k] if k<len(c) else 0)-sum(c[j]*b[k-j] for j in range(1,min(k,len(c)-1)+1))
 return b
def trace_coefficients(c,n):
 d=len(c)-1
 if d==0:return [0]*(n+1)
 M=[[-v for v in c[1:]]]+[[int(j==i-1)for j in range(d)]for i in range(1,d)]
 P=[[int(i==j)for j in range(d)]for i in range(d)];out=[0]
 for k in range(n):
  P=[[sum(P[i][j]*M[j][l]for j in range(d))for l in range(d)]for i in range(d)]
  out.append(-sum(P[i][i]for i in range(d)))
 return out

def main():
 mp.mp.dps=110;L=mp.log(2);rng=random.Random(199)
 prior=json.loads((H/'global1111/results.json').read_text())
 for k,c in corrections.items():assert c==prior['orders'][k]['extra_coefficients']
 cases={1,2,3,2**128}
 cases.update(rng.randrange(1,2**128)for _ in range(1024))
 for j in range(13):
  for m in (1,2,3,5,17,256):
   n=(1<<j)*m**8;cases.update((n-1,n,n+1))
 cases.discard(0)
 print('Exact C-floor versus odd/F2 counts:',len(cases),'arguments',flush=True)
 for x in cases:
  for k in Q:assert raw_count(k,x)==odd_count(k,x),(k,x)
 print('Independent odd-m enumeration at 2^128',flush=True)
 limit=2**128;enumerated={k:0 for k in Q};event_count=0
 for m in range(1,65536,2):
  base=m**8;last=(limit//base).bit_length()-1
  for j in range(last+1):
   event_count+=1
   for k in Q:enumerated[k]+=f2(k,j)
 for k in Q:assert enumerated[k]==raw_count(k,limit)
 print('Literal coefficients and all prefix counts to 2^18',flush=True)
 small=2**18;totals={k:0 for k in Q}
 for n in range(1,small+1):
  v=(n&-n).bit_length()-1;odd=n>>v;r=root8(odd)
  if r**8==odd:
   for k in Q:totals[k]+=f2(k,v)
  for k in Q:assert totals[k]==raw_count(k,n),(k,n)
 b={k:local_coefficients(c,128)for k,c in corrections.items()}
 for k in Q:assert b[k]==trace_coefficients(corrections[k],128)
 print('Independent integer companion traces agree for all 128 local coefficients',flush=True)
 roots={}
 for k,q in Q.items():
  if k=='E8':roots[k]=[];continue
  poly=list(reversed(q));rr=[]
  for z in np.roots(poly):
   guess=mp.mpc(float(z.real),float(z.imag));r=mp.findroot(lambda w:mp.polyval(poly,w),(guess,guess*(1+mp.mpf('1e-5'))),tol=mp.mpf('1e-100'),maxsteps=100)
   assert all(abs(r-v)>mp.mpf('1e-50')for v in rr);rr.append(r)
  rr += [mp.exp(mp.j*mp.pi*(2*j+1)/4)for j in range(4)]
  roots[k]=rr
 root_geom_error=mp.mpf(0);root_residual=mp.mpf(0)
 for k,rr in roots.items():
  for r in rr:root_residual=max(root_residual,abs(mp.polyval(list(reversed(corrections[k])),r)))
  for m in (0,1,2,4,8,16,32,64,128):
   exact=L*sum(b[k][1:m+1]);geom=-L*sum((a:=1/r)*(1-a**m)/(1-a)for r in rr)
   root_geom_error=max(root_geom_error,abs(exact-geom)/(1+abs(exact)))
 assert root_geom_error<mp.mpf('1e-70')
 print('Local roots/geometric sums independently recover signed coefficients',flush=True)
 # Certified previous brackets, not freshly assumed locations for unknown zeros.
 zs=[]
 for z in prior['inherited'][:100]:
  lo,hi=Fraction(z['lower'])*8,Fraction(z['upper'])*8
  zs.append((mp.mpf(lo.numerator)/lo.denominator+mp.mpf(hi.numerator)/hi.denominator)/2)
 rho=np.array([.5+1j*float(t)for t in zs]);mp_rho=[mp.mpc(mp.mpf('.5'),t)for t in zs]
 X=[int(round(2.0**float(u)))for u in np.linspace(16.37,64.37,513)]
 ymax=math.ceil(max(float(mp.root(x,8))for x in X))+1
 sieve=np.ones(ymax+1,dtype=bool);sieve[:2]=False
 for p in range(2,isqrt(ymax)+1):
  if sieve[p]:sieve[p*p::p]=False
 primes=np.where(sieve)[0];lambdas=np.zeros(ymax+1)
 for p in primes:
  power=int(p)
  while power<=ymax:lambdas[power]=log(int(p));power*=int(p)
 prefix=np.cumsum(lambdas)
 trial_primes=[p for p in range(2,ymax+1)if all(p%d for d in range(2,isqrt(p)+1))]
 assert list(primes)==trial_primes
 rawerr={k:[]for k in Q};ys=[];psis=[];exact_wave=[];trunc={str(n):[]for n in (5,20,100)};numpy_mp_error=mp.mpf(0);psi_double_error=mp.mpf(0)
 mu={k:sum(mp.mpf(c)*mp.power(2,-mp.mpf(j)/8)for j,c in enumerate(cs))for k,cs in corrections.items()}
 for index,x in enumerate(X):
  y=mp.root(x,8);ys.append(float(y));r=root8(x);pp=mp.mpf(0)
  for p in trial_primes:
   power=p
   while power**8<=x:
    pp+=mp.log(p)*(mp.mpf('.5')if power**8==x else 1);power*=p
  psis.append(float(8*pp));check=prefix[r]-(lambdas[r]/2 if r**8==x else 0);psi_double_error=max(psi_double_error,abs(pp-check))
  smallterm=-8*mp.log(2*mp.pi)-4*mp.log(1-y**-2)
  exact_wave.append(float((8*pp-8*y-smallterm)/(8*mp.sqrt(y))))
  np_sums=np.cumsum(np.exp(rho*float(mp.log(y)))/rho);mp_sum=mp.mpc(0)
  for j,z in enumerate(mp_rho,1):
   mp_sum+=mp.exp(z*mp.log(y))/z
   if j in (5,20,100):
    approx=8*y+smallterm-16*mp.re(mp_sum);np_approx=8*float(y)+float(smallterm)-16*np_sums[j-1].real
    numpy_mp_error=max(numpy_mp_error,abs(approx-np_approx));trunc[str(j)].append(float(-2*mp.re(mp_sum)/mp.sqrt(y)))
  for k,c in corrections.items():
   a=raw_count(k,x);assert a==odd_count(k,x);err=mp.mpf(a)-mu[k]*y
   assert -sum(c)<err<=mp.mpf('1e-90');rawerr[k].append(float(err/sum(c)))
  if index%128==0:print('Wave grid',index,'/512',flush=True)
 assert numpy_mp_error<mp.mpf('1e-9') and psi_double_error<mp.mpf('1e-10')
 metrics={}
 for n,v in trunc.items():
  diff=np.array(v)-np.array(exact_wave);metrics[n]=dict(normalized_rms=float(np.sqrt(np.mean(diff**2))),normalized_max=float(max(abs(diff))))
 # Symmetric vertical-column cutoffs, separately from the exact geometric reconstruction.
 column_checks=[]
 for k,rr in roots.items():
  if not rr:continue
  alpha=np.array([complex(1/r)for r in rr]);aa=np.log(alpha);const=float(L*sum(mp.mpf(j)*v for j,v in enumerate(corrections[k]))/sum(corrections[k]))
  for u in (.37,4.37,12.37):
   exact=float(L*sum(b[k][1:math.floor(u)+1]));scale=1+sum(abs(complex(-L*(1/r)*(1-(1/r)**math.floor(u))/(1-1/r)))for r in rr)
   for cut in (64,256,1024):
    ns=np.arange(-cut,cut+1);z=aa[:,None]+2j*np.pi*ns[None,:];approx=const-(float(L)*np.sum(np.exp(z*u)/z)).real
    column_checks.append(dict(kind=k,u=u,cut=cut,exact=exact,reconstruction=float(approx),scaled_absolute_error=abs(approx-exact)/scale))
 snapshots={k:dict(A=str(raw_count(k,limit)),main=mp.nstr(mu[k]*mp.root(limit,8),35),error=mp.nstr(raw_count(k,limit)-mu[k]*mp.root(limit,8),30),bound=sum(c),b4=b[k][4],mu=mp.nstr(mu[k],35),local_rightmost_sigma=max([float(-mp.log(abs(r))/L)for r in roots[k]],default=None))for k,c in corrections.items()}
 report=dict(status='Exact factor-derived counts; signed diagnostic is not an ideal/prime-ideal count; finite numerical zero truncations, not certified remainder bounds',bound=str(limit),bound_label='2^128',coefficients=corrections,independent_count_arguments=len(cases),literal_all_prefix_bound=small,independent_odd_m_events_at_bound=event_count,local_coefficients={k:[str(v)for v in values]for k,values in b.items()},local_trace_exact_agreement=True,root_geometric_relative_error=mp.nstr(root_geom_error,8),root_polynomial_residual=mp.nstr(root_residual,8),numpy_mpmath_zero_sum_max_difference=mp.nstr(numpy_mp_error,8),psi_sieve_trial_max_difference=mp.nstr(psi_double_error,8),snapshots=snapshots,truncation_metrics=metrics,column_truncation_checks=column_checks,grid=dict(x=[str(x)for x in X],u=[log(x,2)for x in X],y=ys,count_error_normalized=rawerr,shared_exact_normalized=exact_wave,shared_truncations=trunc,shared_exact_B=psis),source_global_sha256=hashlib.sha256((H/'global1111/results.json').read_bytes()).hexdigest(),zero_count=100,zero_gamma_last=float(zs[-1]),sources=prior['sources'],sources_note='Inherited bracket endpoints multiplied by8 to recover ordinary ordinates; 100 pairs already certified on Re=1/2, no assertion about all zeros')
 (R/'results.json').write_text(json.dumps(report,indent=2)+'\n')
 print(json.dumps(dict(snapshots=snapshots,truncation_metrics=metrics,numpy_mp_error=str(numpy_mp_error),root_geom_error=str(root_geom_error)),indent=2),flush=True)
if __name__=='__main__':main()
