"""One-parameter projection on a chosen pair of affine supporting planes. Requires SymPy."""
from itertools import combinations
from collections import Counter
import sympy as S
from projection28 import t
R=S.Rational
def determinants(group):
    M=S.Matrix([list(h[:3]) for h in group]);rhs=S.Matrix([-h[3] for h in group])
    D=M.det();nums=[]
    for j in range(3):
        N=M.copy();N[:,j]=rhs;nums.append(N.det())
    return D,*nums
def project(pair,others):
    factors={};identities=[];tests=Counter()
    def add(expr,kind,indices=()):
        p=S.Poly(expr,t,domain=S.QQ);tests[kind]+=1
        if p.is_zero:identities.append([kind,indices]);return
        assert p.degree()<=5
        for f,m in p.factor_list()[1]:
            coeff=tuple(int(y) for y in f.clear_denoms(convert=True)[1].primitive()[1].all_coeffs())
            factors.setdefault(coeff,[]).append([kind,indices,m])
    H,K=pair
    if not H[2] and not K[2]:
        a,b,_,d=H;A,B,_,C=K
        D=a*B-b*A;U=b*C-d*B;V=d*A-a*C;add(D,'vertical pivot')
        if S.expand(D)!=0:
            for j,(a,b,c,d) in enumerate(others):add(a*U*D+b*V*D+c*U*V+d*D*D,'vertical slack',(j,))
    else:
        if not H[2]:H,K=K,H
        a,b,c,d=H;e,f,g,h=K
        A,B,C=[S.expand(x) for x in (e*c-a*g,f*c-b*g,h*c-d*g)]
        if A==0:a,b=b,a;A,B=B,A;others=[(y,x,z,n) for x,y,z,n in others];H=(a,b,c,d);K=(f,e,g,h)
        add(A,'line pivot')
        if A!=0:
            co=[c*B,a*B-A*b+c*C,a*C-A*d]
            for i,k in enumerate(co):add(k,'quadratic coefficient',(i,))
            add(co[1]**2-4*co[0]*co[2],'tangency')
            ends=[]
            for j,(x,y,z,n) in enumerate(others):
                I,J,L=x*c-a*z,y*c-b*z,n*c-d*z
                alpha,beta=S.expand(J*A-I*B),S.expand(L*A-I*C)
                add(alpha,'slope',(j,));add(beta,'intercept',(j,))
                if alpha!=0:
                    D,U,V,W=determinants((H,K,(x,y,z,n)))
                    add(D,'vertex pivot',(j,));add(D*W-U*V,'vertex contact',(j,))
                    ends.append((j,alpha,beta))
            for (i,x,y),(j,X,Y) in combinations(ends,2):add(x*Y-X*y,'endpoint order',(i,j))
    return dict(factors=[dict(coeff=k,events=v) for k,v in sorted(factors.items())],identities=identities,tests=dict(tests))
def line_at(pair,others,tau):
    """Exact decision on one line over an isolated real number field."""
    sign=tau.sign
    simp=lambda q:q
    value=tau.evaluate
    def sub(h):return list(map(value,h))
    l,k=map(sub,pair);planes=[sub(h) for h in others]
    def det(i,j):return simp(l[i]*k[j]-k[i]*l[j])
    pivot=next(((i,j) for i,j in combinations(range(3),2) if sign(det(i,j))),None)
    if pivot is None:return 'dependent'
    i,j=pivot;g=3-i-j;D=det(i,j);zero=value(0);one=value(1)
    P=[zero]*3;V=[zero]*3;V[g]=one
    P[i]=simp(-det(3,j)/D);P[j]=simp(-det(i,3)/D);V[i]=simp(-det(g,j)/D);V[j]=simp(-det(i,g)/D)
    lo,hi=zero,one  # The free coordinate is a unit-cube coordinate.
    for h in planes:
        d=simp(h[3]+sum(a*b for a,b in zip(h,P)));s=simp(sum(a*b for a,b in zip(h,V)))
        side=sign(s)
        if not side:
            if sign(d)<0:return 'empty'
        else:
            root=simp(-d/s)
            if side>0 and sign(root-lo)>0:lo=root
            if side<0 and sign(root-hi)<0:hi=root
            if sign(hi-lo)<0:return 'empty'
    A=simp(-V[0]*V[1]);B=simp(V[2]-P[0]*V[1]-P[1]*V[0]);C=simp(P[2]-P[0]*P[1])
    points=[lo,hi]
    if sign(A):
        q=simp(-B/(2*A))
        if sign(q-lo)>0 and sign(q-hi)<0:points.append(q)
    signs=[sign((A*x+B)*x+C) for x in points]
    return 'witness' if min(signs)<=0<=max(signs) else 'gap'
class Radius:
    """Arithmetic modulo the minimal polynomial, ordered by its isolated real embedding."""
    def __init__(self,coeff,low,high):
        from sympy.polys.agca.extensions import MonogenicFiniteExtension
        from functools import lru_cache
        self.lo,self.hi=map(R,(low,high))
        self.poly=S.Poly.from_list(coeff,t,domain=S.QQ)
        assert self.poly.is_irreducible and self.poly.count_roots(self.lo,self.hi)==1
        self.field=MonogenicFiniteExtension(self.poly)
        self.alpha=self.field.generator
        self.evaluate=lru_cache(None)(self._evaluate)
        self.sign=lru_cache(None)(self._sign)
    def _evaluate(self,expr):
        return self.field.convert(S.sympify(expr))
    def _sign(self,q):
        if not q:return 0
        coeff=[R(x.numerator,x.denominator) for x in q.rep.to_list()]
        if len(coeff)==1:return 1 if coeff[0]>0 else -1
        while True:
            a=b=R(0)
            for v in coeff:
                products=[x*y for x in (a,b) for y in (self.lo,self.hi)]
                a,b=min(products)+v,max(products)+v
            if a>0:return 1
            if b<0:return -1
            mid=(self.lo+self.hi)/2
            if self.poly.eval(self.lo)*self.poly.eval(mid)<=0:self.hi=mid
            else:self.lo=mid

def isolated(coeff,low,high):return Radius(coeff,low,high)

def study():
    from contacts27 import TRIPLE
    from rayon26 import CUBE,PROBES
    from projection28 import planes
    from pathlib import Path
    from verifier26 import normal
    import json
    read=lambda f:json.loads(Path(__file__).with_name(f+'.json').read_bytes())
    data=read('paires28');abc=read('quintique27');cases=[]
    baseAC=[(t-R(7,27),-R(1,3),1,0),(-R(3,7),-R(11,14)-t,1,R(3,14)+t)]
    baseABC=[(-R(7,27),t-R(1,3),1,0),(R(4,21)-1,-R(1,21)-t,1,R(1,21)+t),(R(4,7)-t-1,R(3,14)-1,1,1+t-R(3,14)-R(4,7))]
    for name,rows,j in [('AC',[TRIPLE[0],TRIPLE[2]],0),('ABC',TRIPLE,3),('AB',TRIPLE[:2],3),('BC',TRIPLE[1:],3)]:
        px,py=PROBES[j];pool=list(dict.fromkeys(planes(rows,R(px,4),R(py,4))))
        geom=[*CUBE,((1,-1,0,0) if px>py else (-1,1,0,0)),((1,1,0,-1) if px+py>4 else (-1,-1,0,1))]
        region=pool+geom
        if name in ('AC','ABC'):
            active=baseAC if name=='AC' else baseABC;obj=data[name] if name=='AC' else abc
            co=obj['polynomial'];lo,hi=obj['isolation'];tau=isolated(co,lo,hi)
        else:
            obj=data[name];T=R(obj['radius']);u,v=R(obj['u']),R(obj['v']);lo=hi=str(T);co=[int(T.q),-int(T.p)];tau=isolated(co,lo,hi)
            def at(h):return [S.sympify(q).subs(t,T) for q in h]
            active=[h for h in pool if any(at(h)[:3]) and sum(x*y for x,y in zip(at(h),(u,v,u*v,1)))==0]
        found=None
        for pair in combinations(active,2):
            others=[h for h in active if h not in pair]+list(CUBE)
            p=project(pair,others)
            if not any(list(f['coeff'])==co for f in p['factors']):continue
            if line_at(pair,region,tau)=='witness':
                found=(pair,p);break
        assert found,name
        pair,p=found
        extra=[]
        for f in p['factors']:
            ex=S.Poly.from_list(f['coeff'],t)
            for (a,b),_ in ex.intervals(eps=R(1,10**8)):
                if a<0 or b>1:continue
                if f['coeff']==tuple(co) and a<=R(hi) and b>=R(lo):continue
                root=isolated(f['coeff'],str(a),str(b));answer=line_at(pair,region,root)
                assert root.hi<tau.lo or root.lo>tau.hi
                extra.append(dict(coeff=f['coeff'],interval=list(map(str,(a,b))),decision=answer,
                                  global_relation='above' if root.lo>tau.hi else 'below'))
        cases.append(dict(name=name,coeff=co,interval=[lo,hi],decision='witness',pair=[[str(x) for x in h] for h in pair],
                          active_count=len(active),plane_count=len(set(region)),projection=p,other=extra))
    return cases
if __name__=='__main__':
    import json
    print(json.dumps(study(),default=str))
