"""Local law and companion controls; run with Sage and the supplied files.
Imports the generator for direct squareful sums only. Prime-field symbols,
additive-convention checks, Gauss--Jacobi and period controls are constructed
separately in finite fields. Not an independent critique verdict.
"""
import json,sys
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.number_field.number_field import CyclotomicField
from sage.rings.complex_arb import ComplexBallField
import generate
import build_check as independent

B=Path(__file__).resolve().parent
rows=json.loads((B/'entries.json').read_text())
data={(r['params']['a'],r['params']['b']):r for r in rows}
results={'prime_additive_checks':[],'squareful_controls':[]}
for pi in independent.prime_ideals(500):
 a,b=independent.coords(pi);n=int(pi.norm());L= CyclotomicField(3*n)
 z=L.gen();om=z**n;F,fw=independent.local_field(pi)
 reps=[(x,0) for x in range(n)] if ZZ(n).is_prime() else [(x,y) for x in range(-a) for y in range(-a)]
 arrays=[[0]*(3*n) for _ in range(4)]
 chi_values={}
 for u,v in reps:
  x=independent.K(u+v*independent.w)
  exp=independent.residue_exp(x,pi)
  if exp is None:continue
  ch=om**exp
  T=(2*a-b)*u+(2*b-a)*v;D=a*v-b*u
  arrays[0][(exp*n+3*T)%(3*n)]+=1
  arrays[1][(exp*n+3*D)%(3*n)]+=1
  arrays[3][(exp*n-3*T)%(3*n)]+=1
  # division by omega means multiplying x by omega^2=(-1,-1).
  U=-u+v;V=-u
  arrays[2][(exp*n+3*((2*a-b)*U+(2*b-a)*V))%(3*n)]+=1
 trace,diff,changed_unit,minus=[L(coefficients) for coefficients in arrays]
 row=data[(a,b)];exact=L(row['exact_coefficients'])
 assert trace==exact and minus==trace
 k=independent.residue_exp(1+2*independent.w,pi)
 assert diff==om**k*trace
 kw=independent.residue_exp(independent.w,pi)
 assert changed_unit==om**kw*trace
 results['prime_additive_checks'].append({'a':a,'b':b,'norm':n,'trace_matches_exact':True,'different_conversion_exponent':k,'minus_generator_invariant':True,'omega_generator_exponent':kw})
# Check source Lemma 3.2 on small local nonunit interactions, retaining zeros.
for pi in [(-2,0),(1,3)]:
 n=generate.norm(pi)
 for ell in [2,3]:
  modulus=(1,0)
  for _ in range(ell):modulus=generate.mul(modulus,pi)
  L,g0,_=generate.exact_sum(modulus)
  assert g0==0
  for k in range(ell+1):
   shift=(1,0)
   for _ in range(k):shift=generate.mul(shift,pi)
   F,value,_=generate.exact_sum(modulus,shift)
   if ell<=k and ell%3==0:expected=F(n**ell-n**(ell-1))
   elif ell==k+1 and ell%3==0:expected=F(-n**k)
   elif ell==k+1 and ell%3==1:expected=n**k*F(generate.exact_sum(pi)[1])
   elif ell==k+1 and ell%3==2:expected=n**k*F(generate.exact_sum(pi)[1].conjugate())
   else:expected=F(0)
   assert value==expected,(pi,ell,k,value,expected)
   results['squareful_controls'].append({'prime':pi,'modulus_exponent':ell,'shift_exponent':k,'exact_local_law':True,'nonzero':bool(value)})
# The copied Sage Programs example must reproduce the attached sum.
env={}
exec((B/'program-example.py').read_text(),env)
assert env['G']==CyclotomicField(21)(data[(1,3)]['exact_coefficients'])
# Validate actual T142 context, preserving its stored uncertainty.
T142=json.loads((B/'T142-control.json').read_text());s=T142['number']
L=env['L'];independent.stored_contains(s,independent.eval_exact(L,env['G']))
results['T142_7_2_interval_contains_exact_G3_1_3']=True
# Exact Gauss--Jacobi and ordered period identities, independently in F_7.
p=7;L=CyclotomicField(21);z=L.gen();om=z**7
chi={0:L(0)}
for x in range(1,7):chi[x]=om**{1:0,2:1,4:2}[pow(x,2,7)]
G=sum(chi[x]*z**(3*x) for x in range(7))
Gbar=sum(chi[x].conjugate()*z**(3*x) for x in range(7))
J=sum(chi[x]*chi[(1-x)%7] for x in range(7))
assert G*G==J*Gbar
periods=[sum(z**(3*pow(3,j+3*t,7)) for t in range(2)) for j in range(3)]
assert sum(chi[pow(3,j,7)]*periods[j] for j in range(3))==G
assert G==env['G'];results['gauss_jacobi_F7_exact']=True;results['ordered_period_F7_exact']=True
# Both conjugate ideal coordinates are present and values conjugate exactly.
for (a,b),r in data.items():
 rc=data[(a-b,-b)];L=CyclotomicField(3*r['norm'])
 assert independent.conjugate_exact(L,L(r['exact_coefficients']))==L(rc['exact_coefficients'])
results['conjugation_checks']=176
print('RESULT',json.dumps(results),flush=True)
