#!/usr/bin/env python3
"""Exact maximal-order basis controls; numerical ideal-zeta lines and central limits."""
from fractions import Fraction as F
from pathlib import Path
import json,math
import mpmath as mp
R=Path(__file__).resolve().parent;mp.mp.dps=80
one=(F(1),F(0),F(0),F(0));i=(F(0),F(1),F(0),F(0));j=(F(0),F(0),F(1),F(0))
def mul(a,b,m):
 w,x,y,z=a;W,X,Y,Z=b
 return (w*W-x*X-m*(y*Y+z*Z),w*X+x*W+m*(y*Z-z*Y),w*Y+y*W+z*X-x*Z,w*Z+z*W+x*Y-y*X)
def determinant(a):
 a=[list(row) for row in a];d=F(1)
 for k in range(len(a)):
  pivot=next(j for j in range(k,len(a)) if a[j][k])
  if pivot!=k:a[pivot],a[k]=a[k],a[pivot];d=-d
  v=a[k][k];d*=v
  for row in range(k+1,len(a)):
   c=a[row][k]/v
   for col in range(k+1,len(a)):a[row][col]-=c*a[k][col]
 return d
def Z(s,primes):
 if s==mp.mpf('.5') and len(primes)==1:return -mp.log(primes[0])/2
 if s==mp.mpf('.5') and len(primes)>1:return mp.mpf(0)
 return mp.zeta(2*s)*mp.zeta(2*s-1)*mp.fprod(1-p**(1-2*s) for p in primes)
def completed(s,primes):
 D=math.prod(primes)
 return D**s*2**(2-2*s)*mp.pi**(1-2*s)*mp.gamma(2*s)*Z(s,primes)
rec=dict(source='Voight, Quaternion Algebras, Theorem 26.4.9 and equations 26.8.12-14',
 norm='absolute ideal index [O:I], not reduced norm; [O:I]=nrd(I)^2',
 formula='Z_D(s)=zeta(2s)zeta(2s-1) product_(p|D)(1-p^(1-2s))',
 completion='D^s * 2^(2-2s) * pi^(1-2s) * Gamma(2s) * Z_D(s)',
 completion_mirror='s <-> 1-s for these definite rational quaternion algebras',orders=[],precision_digits=80)
for p in [2,3]:
 m=1 if p==2 else 3
 basis=[one,i,j,(F(1,2),F(1,2),F(1,2),F(1,2))] if p==2 else [one,i,(F(1,2),F(0),F(1,2),F(0)),(F(0),F(1,2),F(0),F(1,2))]
 table=[]
 for a in basis:
  row=[]
  for b in basis:
   x=mul(a,b,m)
   cs=(x[0]-x[3],x[1]-x[3],x[2]-x[3],2*x[3]) if p==2 else (x[0]-x[2],x[1]-x[3],2*x[2],2*x[3])
   assert all(c.denominator==1 for c in cs);row.append([int(c) for c in cs])
  table.append(row)
 gram=[[2*mul(a,b,m)[0] for b in basis] for a in basis]
 det=determinant(gram);assert abs(det)==p*p
 central=-mp.log(p)/2;near=[]
 for h in ['1e-6','-1e-6','1e-12','-1e-12','1e-24','-1e-24']:
  hh=mp.mpf(h);v=Z(mp.mpf('.5')+hh,[p]);assert abs(v-central)<20*abs(hh)
  near.append(dict(offset=h,value=str(v),error_from_limit=str(abs(v-central))))
 # Exact ideal-count coefficients from local factors, independently summing the positive series.
 M=5000;coef=[0]*(M+1)
 for d in range(1,M+1):
  if d%p:
   for n in range(d,M+1,d):coef[n]+=d
 partial=sum(mp.mpf(coef[n])/n**4 for n in range(1,M+1));tail=(mp.log(M)/2+mp.mpf(3)/4)/M**2
 assert abs(Z(mp.mpf(2),[p])-partial)<tail
 zeros=[]
 for n in range(1,9):
  rho=mp.zetazero(n)
  for kind,s in [('quarter',rho/2),('three_quarters',(rho+1)/2)]:
   residual=abs(Z(s,[p]));assert residual<mp.mpf('1e-65')
   zeros.append(dict(kind=kind,real=str(mp.re(s)),height=str(mp.im(s)),absolute_residual=str(residual),riemann_zero_index=n))
 for k in range(1,9):
  s=mp.mpf('.5')+1j*mp.pi*k/mp.log(p);v=Z(s,[p]);assert abs(v)<mp.mpf('1e-65')
  zeros.append(dict(kind='ramified_local_half',real='0.5',height=str(mp.im(s)),absolute_residual=str(abs(v)),local_index=k))
 fe=[]
 for s in [mp.mpc('.2','.7'),mp.mpc('.5','1.3'),mp.mpc('.8','2.1')]:
  err=abs(completed(s,[p])-completed(1-s,[p]));assert err<mp.mpf('1e-70');fe.append(dict(s=str(s),error=str(err)))
 rec['orders'].append(dict(reduced_discriminant=p,algebra='(-1,-'+str(m)+') over Q',
  ramified_places=[str(p),'infinity'],basis=[[str(c) for c in b] for b in basis],basis_closed=True,
  multiplication_table=table,trace_gram=[[str(c) for c in row] for row in gram],trace_discriminant=str(det),
  maximality='Reduced order discriminant equals the independently known algebra discriminant; index formula implies maximality',
  central_value_exact='-log('+str(p)+')/2',central_value=str(central),central_value_verified=True,central_nearby_checks=near,
  half_line_spacing=str(mp.pi/mp.log(p)),zero_samples=zeros,first_20_ideal_coefficients=coef[1:21],
  positive_series_check=dict(s='2',cutoff=M,partial=str(partial),factor_value=str(Z(mp.mpf(2),[p])),proved_tail_bound=str(tail)),functional_equation_checks=fe))
# An even central zero from three finite ramified primes is a different mechanism from Q8's odd sign.
coefficient=-2*mp.log(2)*mp.log(3)*mp.log(5);checks=[]
for h in ['1e-5','1e-10','1e-20']:
 hh=mp.mpf(h);value=Z(mp.mpf('.5')+hh,[2,3,5])/hh**2;assert abs(value-coefficient)<100*hh
 checks.append(dict(h=h,quotient=str(value),error=str(abs(value-coefficient))))
rec['ramified_central_control']=dict(discriminant=30,ramified_places=['2','3','5','infinity'],central_order=2,
 exact_leading_coefficient='-2 log(2) log(3) log(5)',leading_coefficient=str(coefficient),checks=checks,
 warning='Known factorization consequence checked here, not a newly discovered general theorem; not the Q8 Artin root-sign mechanism.')
rec['line_scope']='The local half-line roots are unconditional. The two inherited nontrivial families are rho/2 and (rho+1)/2; RH would put all such families on 1/4 and 3/4. Sampled Riemann zeros here are numerical, not new interval certificates.'
(R/'quaternion-orders-results.json').write_text(json.dumps(rec,indent=2)+'\n')
print('PASS explicit maximal bases D2,D3, 48 numerical zero samples, central limits, FE; D30 central double-zero control',flush=True)
