"""Builder's second implementation: exact quadratic arithmetic and log series.

Run python3 check_values.py computed-rows.json [stored-document.json].
Does not import generate.py or certified_log.py and uses no Sage or PARI.
Hensel uses Newton precision doubling; log uses exact powers with denominator
cancellation and stops at k=3N. Main generator uses digit lifting and 2N terms.
This checks build evidence; it is not the controller's independent critique.
"""
import json,sys,math,hashlib,re
from types import SimpleNamespace
from pathlib import Path

def ordp(a,p):
    if a==0:return 10**6
    n=0
    while a%p==0:a//=p;n+=1
    return n

def logfloor(a,p):
    k=0
    while p**(k+1)<=a:k+=1
    return k

def root(D,p,M,r0):
    r=r0;n=1
    while n<M:
        n=min(2*n,M);mod=p**n
        r=(r-(r*r-D)*pow(2*r,-1,mod))%mod
        assert (r*r-D)%mod==0
    return r

def logarithm(u,p,N,M):
    mod=p**M;outmod=p**N
    assert u%p
    z=(pow(u,p-1,mod)-1)%mod
    assert z%p==0
    zpow=1;s=0
    for k in range(1,3*N):
        zpow=zpow*z%mod;e=ordp(k,p)
        assert M-e>=N
        s=(s+(-1 if k%2==0 else 1)*(zpow//p**e)*pow(k//p**e,-1,outmod))%outmod
    assert 3*N-logfloor(3*N,p)>=N
    return s*pow(p-1,-1,outmod)%outmod

def value(D,p,x,y,w,N,r0,embedding_only=False):
    h=ordp((x*x-D*y*y)//4,p);M=N+h+logfloor(3*N,p)+8;mod=p**M
    r=root(D,p,M,r0);u=(x+y*r)*pow(2,-1,mod)%mod
    if embedding_only:
        assert ordp(u,p)==h
        u//=p**h;M-=h
    else:assert u%p
    return 4*logarithm(u,p,N,M)*pow(w,-1,p**N)%p**N

def kronecker(D,a):
    # Euler/Jacobi using a's prime factorization, independent of Sage and helper.
    answer=1;q=2;n=a
    while q*q<=n:
        e=0
        while n%q==0:n//=q;e+=1
        if e:
            if D%q==0:return 0
            s=(1 if D%8 in (1,7) else -1) if q==2 else (1 if pow(D%q,(q-1)//2,q)==1 else -1)
            answer*=s**e
        q+=1
    if n>1:
        if D%n==0:return 0
        s=(1 if D%8 in (1,7) else -1) if n==2 else (1 if pow(D%n,(n-1)//2,n)==1 else -1)
        answer*=s
    return answer

def squarefree(n):return not any(n%(k*k)==0 for k in range(2,math.isqrt(n)+1))
def isfund(D):return (D%4==1 and squarefree(abs(D))) or (D%4==0 and (D//4)%4 in (2,3) and squarefree(abs(D)//4))

def expected():
    return [(D,p) for D in range(-3,-44,-1) if isfund(D) for p in range(5,44) if all(p%d for d in range(2,math.isqrt(p)+1)) and kronecker(D,p)==1]

def accept(residue,truth,p,N):return (residue-truth)%p**N==0

def main():
    rows=json.loads(Path(sys.argv[1]).read_text());results=[];failures=[];stored={}
    if len(sys.argv)>2:
        sys.path.insert(0,str(Path.cwd()))
        from numberdb_app.flatten import to_records
        document=json.loads(Path(sys.argv[2]).read_text())
        for row in to_records(document):
            D=int(row['params']['D']);p=int(row['params']['p'])
            # Use the client parser for storage syntax, not for computation.
            sys.path.insert(0,str(Path.cwd()/'clients/python'))
            import numberdb
            text=str(row['number']).replace(' ','')
            match=re.fullmatch(r'(\d+)(?:\^(\d+))?\*(\d+)\+O\((\d+)\^(\d+)\)',text)
            assert match,text
            pp,v,unit,pp2,N=match.groups();assert pp==pp2
            val=SimpleNamespace(prime=int(pp),valuation=int(v or 1),unit=int(unit),precision_absolute=int(N))
            stored[D,p]=val
    assert [(r['D'],r['p']) for r in rows]==expected()
    assert len(rows)==75
    controls={}
    p=7;N=4;mod=p**N
    known=(7-49*pow(2,-1,mod)+343*pow(3,-1,mod))%mod
    controls['known_nonzero_log']=logarithm(8,p,N,20)==known and known!=0
    controls['root_of_unity_log']=logarithm(pow(5,20)-1,5,8,20)==0
    all_last=True;all_sign=True;unit_invariance=True;conjugation=True
    for row in rows:
        D,p,h,w,r0,x,y,N=[row[k] for k in ['D','p','h','w','r0','x','y','absolute_precision']]
        residue=int(row['residue']);truth=value(D,p,x,y,w,N,r0)
        assert isfund(D) and r0==min(r for r in range(1,p) if (r*r-D)%p==0)
        assert x*x-D*y*y==4*p**h and (D%4!=1 or (x-y)%2==0) and (D%4!=0 or x%2==0)
        assert w==(6 if D==-3 else 4 if D==-4 else 2)
        assert -sum(kronecker(D,a)*a for a in range(1,-D+1))*w==(-D)*2*h
        assert p**row['relative_precision']>=10**100 and p**(row['relative_precision']-1)<10**100
        assert ordp(residue,p)==row['valuation'] and N-row['valuation']==row['relative_precision']
        assert truth==residue==int(row['gamma_residue'])
        all_last &= not accept(residue+p**(N-1),truth,p,N)
        sign=value(D,p,x,y,w,N,p-r0,True)
        all_sign &= sign==(-truth)%p**N and not accept(sign,truth,p,N)
        conjugation &= value(D,p,x,-y,w,N,p-r0)==truth
        unit_invariance &= value(D,p,-x,-y,w,N,r0)==truth
        # Extra roots of unity in the two exceptional fields.
        if D==-4:
            unit_invariance &= value(D,p,-2*y,x//2,w,N,r0)==truth
            # Instead evaluate exact multiplication by sqrt(D)/2 using rational coefficients below.
        if D in (-3,-4):
            M=N+20;mod=p**M;r=root(D,p,M,r0);u=(x+y*r)*pow(2,-1,mod)%mod
            eps=(1+r)*pow(2,-1,mod)%mod if D==-3 else r*pow(2,-1,mod)%mod
            unit_invariance &= 4*logarithm(u*eps%mod,p,N,M)*pow(w,-1,p**N)%p**N==truth
        if stored:
            v=stored[D,p];assert v.prime==p and v.precision_absolute==N and v.valuation==row['valuation']
            assert (v.unit*p**v.valuation-truth)%p**N==0
        results.append({'D':D,'p':p,'absolute_precision':N,'full_modulus_match':True,'stored_checked':bool(stored)})
    controls.update(last_digit_perturbations_rejected=all_last,embedding_only_rejected=all_sign,coherent_conjugation=conjugation,global_unit_invariance=unit_invariance)
    r=next(r for r in rows if (r['D'],r['p'])==(-3,7));N=r['absolute_precision'];M=N+20;mod=7**M;rr=root(-3,7,M,r['r0']);u=(r['x']+r['y']*rr)*pow(2,-1,mod)%mod
    raw=logarithm(u,7,N,M);controls['missing_roots_of_unity_factor_rejected']=raw!=int(r['residue'])
    # A principal split prime in a field of class number 2 discriminates h from ideal order.
    controls['unadjusted_smaller_ideal_power_rejected']=False
    for r in rows:
        if r['h']<2:continue
        D,p,h=r['D'],r['p'],r['h']
        for yy in range(-math.isqrt(4*p//(-D)),math.isqrt(4*p//(-D))+1):
            xx=4*p+D*yy*yy
            if xx<0:continue
            x=math.isqrt(xx)
            if x*x==xx and ((D%4==1 and (x-yy)%2==0) or (D%4==0 and x%2==0)) and (x+yy*r['r0'])%p:
                v=value(D,p,x,yy,r['w'],r['absolute_precision'],r['r0'])
                if v!=int(r['residue']):
                    controls['unadjusted_smaller_ideal_power_rejected']=True
                    controls['smaller_power_example']={'D':D,'p':p,'h':h,'ideal_order':1,'x':x,'y':yy}
                    break
        if controls['unadjusted_smaller_ideal_power_rejected']:break
    assert all(v for k,v in controls.items() if isinstance(v,bool)),controls
    out={'checked_entries':len(results),'total_entries':len(rows),'failures':failures,'known_answer_control':controls['known_nonzero_log'] and controls['root_of_unity_log'],'negative_control_rejected':all_last and all_sign and controls['missing_roots_of_unity_factor_rejected'] and controls['unadjusted_smaller_ideal_power_rejected'],'controls':controls,'rows':results,'stored_entries':len(stored),'limitation':'Builder check, not an independent critique verdict.'}
    outpath=Path(sys.argv[1]).with_name('stored-check-results.json' if stored else 'check-results.json');outpath.write_text(json.dumps(out,indent=2)+'\n');print(json.dumps({k:v for k,v in out.items() if k!='rows'},indent=2))

if __name__=='__main__':main()
