"""Independent builder checks. Sage 10.9 + numberdb; no generator imports.
Run: sage -python build_check.py entries.json [stored-document.json]
The wrapper mode reads matching files beside this script. Exact split-prime
controls use the unweighted cubic exponential sum, not cubic characters.
Independent finite residue fields supply CRT phases. Exact algebraic tests
and rigorous checks of the intervals in the decimal strings are both made.
This is builder evidence, not an independent critique verdict.
"""
import json,sys,os,re,hashlib
from pathlib import Path
from fractions import Fraction
from itertools import combinations
from math import isqrt
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.number_field.number_field import CyclotomicField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.env import SAGE_VERSION
from sage.rings.real_mpfi import RealIntervalField

BASE=Path(__file__).resolve().parent
K=CyclotomicField(3);w=K.gen();C=ComplexBallField(640)
wc=(C(0,2)*C.pi()/3).exp()


def coords(x):
 return tuple(int(y) for y in list(K(x)))


def primary(x):
 possible=[]
 for j in range(6):
  y=x*(-w)**j;a,b=coords(y)
  if a%3==1 and b%3==0:possible.append(y)
 assert len(possible)==1
 return possible[0]


def prime_ideals(limit):
 primes=[]
 for p in range(2,limit+1):
  if p==3 or not ZZ(p).is_prime():continue
  for I,e in K.ideal(p).factor():
   if I.norm()>limit:continue
   x=primary(I.gens_reduced()[0]);assert K.ideal(x)==I
   primes.append(x)
 return sorted(primes,key=lambda x:(x.norm(),*coords(x)))


def product_selection(primes,limit):
 # Independent enumeration by subsets of distinct prime ideals.
 choices={}
 def visit(start,current,fs):
  for j in range(start,len(primes)):
   n=primes[j]
   if current.norm()*n.norm()>limit:break
   new=current*n;ident=coords(new)
   assert ident not in choices
   choices[ident]=fs+(n,)
   visit(j+1,new,fs+(n,))
 visit(0,K(1),())
 return choices


field_cache={}
def local_field(pi):
 key=coords(pi)
 if key in field_cache:return field_cache[key]
 a,b=key;n=int(pi.norm())
 if ZZ(n).is_prime():
  F=GF(n);om=-F(a)/F(b)
 else:
  q=isqrt(n);assert q*q==n and q%3==2
  R=PolynomialRing(GF(q),'t');t=R.gen()
  F=GF(q*q,'u',modulus=t*t+t+1);om=F.gen()
 assert om**3==1 and om!=1
 field_cache[key]=(F,om)
 return F,om


def residue_exp(x,pi):
 F,om=local_field(pi);a,b=coords(x);y=F(a)+F(b)*om
 if y==0:return None
 t=y**((int(pi.norm())-1)//3)
 roots=[F(1),om,om**2];assert t in roots
 return roots.index(t)


def exact_record(row):
 n=row['norm'];L=CyclotomicField(3*n)
 return L,L(row['exact_coefficients'])


def conjugate_exact(L,x):
 # zeta_m -> zeta_m^(-1). Permute exponents, then reduce once in L.
 order=int(L.gen().multiplicative_order());coefficients=[0]*order
 for j,c in enumerate(x):coefficients[(-j)%order]+=c
 return L(coefficients)


def embed_exact(L,x):
 source_order=int(x.parent().gen().multiplicative_order())
 target_order=int(L.gen().multiplicative_order())
 assert target_order%source_order==0
 ratio=target_order//source_order;coefficients=[0]*target_order
 for j,c in enumerate(x):coefficients[(ratio*j)%target_order]+=c
 return L(coefficients)


def eval_exact(L,x):
 # The defining generator is exp(2*pi*i/(3*N)); the field's full unit-root
 # order can be twice that conductor and must not be substituted here.
 order=int(L.gen().multiplicative_order())
 root=(C(0,2)*C.pi()/order).exp();result=C(0)
 for a in reversed(list(x)):result=result*root+C(a)
 assert result.real().is_finite() and result.imag().is_finite()
 assert result.accuracy()>500
 return result


def component_interval(s):
 s=s.strip()
 # Exact integers/rationals remain points. A decimal has one last-place ulp.
 if '.' not in s and 'e' not in s.lower():
  q=Fraction(s);return q,q
 q=Fraction(s)
 mantissa,sep,exp=s.lower().partition('e');exponent=int(exp) if sep else 0
 places=len(mantissa.partition('.')[2])
 ulp=Fraction(10)**(exponent-places)
 return q-ulp,q+ulp


def stored_parts(s):
 s=s.replace(' ','')
 if '+i*' in s:r,i=s.split('+i*')
 elif '-i*' in s:r,i=s.split('-i*');i='-'+i
 elif s.startswith('i*'):r,i='0',s[2:]
 else:r,i=s,'0'
 return component_interval(r),component_interval(i)


def stored_contains(s,z):
 for part,(lo,hi) in zip((z.real(),z.imag()),stored_parts(s)):
  assert part.is_finite()
  if lo==hi:
   # Exact-point claim is separately certified by the exact algebraic tests.
   assert QQ(lo.numerator)/lo.denominator in part
  else:
   assert part.accuracy()>500
   assert QQ(lo.numerator)/lo.denominator < QQ(part.lower())
   assert QQ(part.upper()) < QQ(hi.numerator)/hi.denominator
 return True


def run(rows,stored=None):
 for m in [12,21,39]:
  L=CyclotomicField(m);x=L.gen()+2*L.gen()**3
  assert conjugate_exact(L,x)==x.conjugate()
 assert embed_exact(CyclotomicField(21),CyclotomicField(3).gen())==CyclotomicField(21).gen()**7
 primes=prime_ideals(500);selected=product_selection(primes,500)
 identities=[(int(r['params']['a']),int(r['params']['b'])) for r in rows]
 assert set(identities)==set(selected) and len(identities)==len(selected)==176
 assert identities==sorted(identities,key=lambda t:(int(K(t[0]+t[1]*w).norm()),*t))
 data={ident:(*exact_record(row),row) for ident,row in zip(identities,rows)}
 prime_exact={};checks=[]
 split=inert=0
 for pi in primes:
  ident=coords(pi);L,v,row=data[ident];n=int(pi.norm());om=L.gen()**n
  assert v**3==-n*(ident[0]+ident[1]*om)
  if ZZ(n).is_prime():
   counts=[0]*n
   for x in range(n):counts[pow(x,3,n)]+=1
   # Embed zeta_p=zeta_(3p)^3, selecting its positive exponential embedding.
   polynomial=[0]*(3*n)
   for j,count in enumerate(counts):polynomial[3*j]=count
   S=L(polynomial)
   assert v+conjugate_exact(L,v)==S
   # This rejects both other cubic roots: all three real parts differ.
   assert om*v+conjugate_exact(L,om*v)!=S
   assert om**2*v+conjugate_exact(L,om**2*v)!=S
   split+=1
  else:
   q=isqrt(n);assert v==q;inert+=1
  prime_exact[ident]=v
  print('CHECKPOINT_PRIME',json.dumps({'params':ident,'norm':n,'independent_phase':True}),flush=True)
 composite=0
 for ident in identities:
  L,v,row=data[ident];a,b=ident;c=K(a+b*w);fs=selected[ident]
  expected=L(1);partial=K(1);om=L.gen()**row['norm']
  for pi in fs:
   exponent=residue_exp(partial,pi)
   assert exponent is not None
   expected*=om**((-exponent)%3)*embed_exact(L,prime_exact[coords(pi)])
   partial*=pi
  assert partial==c and expected==v,(ident,'CRT disagreement')
  assert v**3==(-1)**len(fs)*row['norm']*(a+b*om)
  assert v*conjugate_exact(L,v)==row['norm']
  z=eval_exact(L,expected)
  number=row['number'] if stored is None else stored[ident]
  stored_contains(number,z)
  if '.' not in number:assert v in QQ and QQ(v)==QQ(number)
  if len(fs)>1:composite+=1
  print('CHECKPOINT_ENTRY',json.dumps({'params':ident,'norm':row['norm'],'stored_interval':True}),flush=True)
  checks.append({'params':{'a':a,'b':b},'norm':row['norm'],'factor_count':len(fs),'exact_cube':True,'exact_norm':True,'independent_phase':True,'stored_interval_contains_independent_ball':True})
 assert (split,inert,composite)==(90,4,82)
 # Concrete correct and wrong CRT phases at norm 91.
 c=K(1+3*w);d=K(4+3*w);ident=coords(c*d);L,v,_=data[ident]
 assert residue_exp(c,d)==1
 assert embed_exact(L,prime_exact[coords(c)])*embed_exact(L,prime_exact[coords(d)])!=v
 # Small exact nonzero control, and a deliberately wrong additive embedding.
 assert data[(-2,0)][1]==2
 L,v,row=data[(1,3)]
 badroot=(C(0,2)*C.pi()/(6*row['norm'])).exp();bad=C(0)
 for coef in reversed(list(v)):bad=bad*badroot+C(coef)
 assert not stored_contains_safe(row['number'],bad)
 # A visibly shifted decimal and a broad/nonfinite ball must be rejected.
 good=eval_exact(L,v)
 assert not stored_contains_safe(row['number'],good+C(1)/10**60)
 assert not stored_contains_safe(row['number'],C(RealIntervalField(640)(-1000,1000)))
 # A change in denominator by omega (not by -1, which the cubic character
 # sends to +1) alters the additive phase when (omega/c)_3 is nontrivial.
 assert residue_exp(w,K(1+3*w)) is not None
 return {'checked_entries':176,'total_entries':176,'failures':[],
         'known_answer_control':True,'negative_control_rejected':True,
         'counts':{'split_prime':split,'inert_prime':inert,'composite':composite},
         'methods':['independent rational-prime ideal factorization and subset enumeration','exact unweighted S_p plus cube root identification for all split primes','inert conjugation and cube relation','independent finite-field CRT character factors','640-bit Horner enclosures inside stored decimal intervals'],
         'controls':['G3(-2)=2','both wrong cube roots rejected at all 90 split prime ideals','norm-91 CRT factor required','wrong full-root-order embedding rejected','10^-60 shift rejected','broad ball rejected'],
         'skill_manifest_sha256':hashlib.sha256((BASE/'skill-manifest.json').read_bytes()).hexdigest(),'software':{'sage':SAGE_VERSION,'python':sys.version.split()[0],'numberdb':numberdb.__version__},'comparisons':checks}


def stored_contains_safe(s,z):
 try:return stored_contains(s,z)
 except (AssertionError,ValueError,TypeError,AttributeError):return False


if __name__=='__main__':
 path=Path(sys.argv[1]) if len(sys.argv)>1 else BASE/'entries.json'
 rows=json.loads(path.read_text());stored=None
 if len(sys.argv)>2:
  document=json.loads(Path(sys.argv[2]).read_text())
  from numberdb._generate import _stored_entries
  stored={tuple(int(x.strip()) for x in key.split(',')):value for key,value in _stored_entries(document).items()}
  assert len(stored)==176
 result=run(rows,stored)
 print('RESULT',json.dumps(result),flush=True)
