"""Check a proposed minimax radius with two fixed-radius proofs. Standard Python."""
from fractions import Fraction as F
from math import gcd,lcm
from pathlib import Path
import json,sys
from verifier29 import rows_at
from verifier26 import verify

PROBES=((2,1),(3,2),(2,3),(1,2))

def rows(laws,j):
    x,y=PROBES[j];probe=(F(x,4),F(y,4))
    for owner,law in enumerate(laws):
        for raw in zip(rows_at([law],probe,0),rows_at([law],probe,1)):
            h=[(x-o,y-o,z-x-y+o,o) for o,x,y,z in raw]
            coeff=[v for a,b in zip(*h) for v in (a,b-a)]
            den=lcm(*(F(x).denominator for x in coeff))
            ints=[int(v*den) for v in coeff];g=gcd(*ints) or 1
            assert ints[5]==0
            yield tuple(v//g for v in ints),owner

def envelope(laws):
    bounds=[]
    for j in range(4):
        cols=[1]*4
        for row,_ in rows(laws,j):
            for i in range(4):cols[i]=max(cols[i],abs(row[2*i])+abs(row[2*i+1]))
        h=max(cols[:2]);c,d=cols[2:]
        p=2*h*c;k=2*d*c
        l=c*p;s=2*h*p+c*k;z=h*k+d*p
        det=6*h*h*c;u=6*h*d*c;w=6*h*h*d
        dv=2*h*h;uv=2*h*d
        bounds.append(max(2,*cols,p,k,l,s,z,s*s+4*l*z,2*p*p,2*p*k,6*p*p*k,det,u,w,det*w+u*u,dv,uv,2*h*uv*dv+c*uv**2+d*dv**2))
    return max(bounds)

def denominator(rows_,coeff):
    k=4 if len(rows_)==2 else 5
    D=(1<<k)*envelope(rows_)
    return k*D**(len(coeff)-1)*sum(map(abs,coeff))**k

def irreducible_modulus(coeff):
    """A prime witnessing the exact degree, when found in this small search."""
    from itertools import product
    for prime in (2,3,5,7,11,13,17,19,23,29,31,37,41):
        if coeff[0]%prime==0:continue
        # Every reducible reduction has a monic factor of degree <= d/2.
        def divides(tail):
            remainder=[c%prime for c in coeff]
            for i in range(len(coeff)-len(tail)):
                lead=remainder[i]
                for j,v in enumerate(tail,1):
                    remainder[i+j]=(remainder[i+j]-lead*v)%prime
            return not any(remainder[-len(tail):])
        if not any(divides(tail) for k in range(1,(len(coeff)-1)//2+1)
                   for tail in product(range(prime),repeat=k)):
            return prime
    return None

def check(record):
    if not __debug__:raise RuntimeError("Run without -O")
    laws=[tuple(map(F,row)) for row in record['laws']]
    assert laws and all(len(row)==4 and min(row)>=0 and sum(row)==1 for row in laws)
    f=record['coeff'];assert 2<=len(f)<=6 and all(type(x) is int for x in f) and f[0]
    low,high=record['endpoints'];a,b=F(low['e']),F(high['e'])
    if 'cap31' in record:
        from separation31 import bound
        cap=F(record['cap31']);assert b<=cap<=1
        separation=bound(laws,f,cap)
    else:separation=denominator(laws,f)
    assert 0<=a<b<=1 and (b-a)*separation<1
    def value(x):
        ans=0
        for c in f:ans=ans*x+c
        return ans
    assert value(a)*value(b)<0
    l=r=0
    for j,c in enumerate(f[:-1]):
        products=[x*y for x in (l,r) for y in (a,b)]
        l,r=min(products)+c*(len(f)-1-j),max(products)+c*(len(f)-1-j)
    assert l>0 or r<0
    assert not low['certificate']['feasible'] and high['certificate']['feasible']
    assert not verify(laws,a,low['certificate']) and verify(laws,b,high['certificate'])
    prime=irreducible_modulus(f)
    if 'irreducible_modulo' in record:assert record['irreducible_modulo']==prime
    return dict(name=record['name'],candidate_degree=len(f)-1,degree=len(f)-1 if prime or len(f)==2 else None,irreducible_modulo=prime,bits=record['bits'],verified=True)

def check_dataset(data):
    if not __debug__:raise RuntimeError('Run without -O')
    cases=data['cases'];assert cases
    indexed={z['name']:z for z in data['certificates']}
    assert len(indexed)==len(data['certificates']) and len({z['name'] for z in cases})==len(cases)
    assert set(indexed)=={z['name'] for z in cases if z['status']=='certified'}
    result=[]
    for z in cases:
        name=z['name']
        if z['status']=='certified':
            candidate=indexed[name]
            assert candidate['laws']==z['laws'] and candidate['coeff']==z['coeff']
            result.append(check(candidate))
        elif z['status']=='zero':
            assert verify(z['laws'],0,z['certificate'])
            result.append(dict(name=name,exact=0,verified=True))
        else:
            assert z['status']=='unresolved'
            result.append(dict(name=name,reason='unresolved',verified=False))
    return result

if __name__=='__main__':
    data=json.loads((Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('decouverte30.json')).read_bytes())
    result=check_dataset(data);print(json.dumps(result))
    sys.exit(0 if all(r['verified'] for r in result) else 1)
