"""Certify the two optimal contact branches throughout the specified weight interval (SymPy)."""
from functools import lru_cache
from fractions import Fraction as F
from pathlib import Path
import json
import sympy as S
from projecteur29 import determinants,t
from verifier29 import rows_at
from contacts27 import TRIPLE
from rayon26 import constraints,clip
from verifier26 import BOX,vertices,permitted
from quintique27 import interval

s=S.Symbol('s'); Q=S.Rational
L,H=Q(-3,32),Q(-11,128)
T0,T1=Q(1912,10000),Q(1914,10000)
k=21+s
laws=[[Q(z,27) for z in (9,5,7,6)],[z/k for z in (1,9+s,7,4)],[Q(z,14) for z in (1,3,2,8)]]
def numerator(expr):return S.cancel(expr).as_numer_denom()[0]
def signed(poly,x):
    p=S.Poly(poly,s);assert not p.is_zero and not p.count_roots(L,H)
    return S.sign(p.eval(x))
def local_sign(expr,poly,x):
    n,d=S.cancel(expr).as_numer_denom()
    f=S.Poly(poly.subs(s,x),t);a,b=f.refine_root(T0,T1,eps=Q(1,2**80))
    def part(v):
        g=S.Poly(v.subs(s,x),t,domain=S.QQ).rem(f)
        if g.is_zero:return 0
        lo,hi=interval(g,a,b)
        if lo<=0<=hi:raise ArithmeticError((v,x))
        return 1 if lo>0 else -1
    dn=part(d);assert dn
    return part(n)*dn

def study():
    old=json.loads(Path(__file__).with_name('croisement31.json').read_bytes())
    root=S.Poly.from_list(old['roots'][0]['coeff'],s);al,ah=map(Q,old['roots'][0]['interval'])
    assert root.is_irreducible and root.count_roots(L,H)==1 and root.count_roots(al,ah)==1
    left=(L+al)/2;right=(ah+H)/2
    # Enlarge the radius of the fixed triple by the TV displacement of B(s).
    tol=F(1,5);assert T1+12*(-L)/(21*(21+L))<tol
    covers=[]
    for j in range(3):
        verts,used=clip(constraints(TRIPLE,tol,j))
        assert not verts and set(used)<=permitted(TRIPLE,tol,j) and not vertices([*BOX,*used])
        covers.append(used)
    events=[list(rows_at([law],(F(1,4),F(1,2)),t)) for law in laws];result=[]
    for branch,ids in enumerate(old['events']):
        hs=[]
        for i,j in ids:
            o,x,y,b=events[i][j]
            hs.append([S.cancel(z*(k if i==1 else 1)) for z in (x-o,y-o,b-x-y+o,o)])
        D,U,V,W=determinants(hs);u,v=S.cancel(U/D),S.cancel(V/D)
        P=S.sympify(old['branches'][branch],locals={'s':s,'t':t})
        assert S.rem(numerator(D*W-U*V),P,t)==0
        # No horizontal-edge zero and no multiple t-root: the root count is constant.
        assert signed(P.subs(t,T0),L)*signed(P.subs(t,T1),L)==-1
        signed(S.resultant(P,S.diff(P,t),t),L)
        assert S.Poly(P.subs(s,L),t).count_roots(T0,T1)==1
        @lru_cache(None)
        def zeros(expr):
            if not expr.has(t):res=expr
            else:res=S.resultant(P,expr,t)
            if res==0:return None
            at_cross=False
            for f,_ in S.factor_list(res)[1]:
                p=S.Poly(f,s)
                if p.count_roots(L,H):
                    assert p.monic()==root.monic(),(p,expr)
                    at_cross=True
            return at_cross
        checks={}
        def certify(label,expr,expected):
            n,d=S.cancel(expr).as_numer_denom()
            nz,dz=zeros(n),zeros(d)
            assert dz is False,(label,'denominator')
            if nz is None:
                assert S.rem(n,P,t)==0 and expected==[0,0]
                signs=[0,0]
            else:
                signs=[local_sign(expr,P,x) for x in (left,right)]
                assert signs==expected,(label,signs,expected)
                if expected[0]!=expected[1]:assert nz
                elif nz: # Exclude a spurious projected root by exact specialization later.
                    assert cross_sign(expr,P,root,al,ah)==signs[0]
            checks[label]=signs
        certify('determinant',D,[local_sign(D,P,L)]*2)
        for label,expr in [('u',u),('v',v),('v-u',v-u),('1-v-u',1-v-u),('v-a3',v-Q(7,27)),('C denominator',1-v-Q(4,7)+t),('slope of A-C',-(Q(1,3)-t)*Q(7,27)/(v-Q(7,27))**2+Q(3,14)*(Q(4,7)-t)/(1-v-Q(4,7)+t)**2)]:
            certify(label,expr,[1,1])
        masses=[1-Q(7,27)/v,laws[1][1]/(1-u) if branch==0 else 1-laws[1][3]/(1-v),Q(3,14)/(1-u)]
        residuals=[]
        for i,(law,m) in enumerate(zip(laws,masses)):
            certify('m'+str(i),m,[1,1]);certify('1-m'+str(i),1-m,[1,1])
            r=[S.cancel(a-b) for a,b in zip((m*u,m*(1-u),(1-m)*v,(1-m)*(1-v)),law)]
            signs=([-1,1,0,1] if i==0 else [1,0,1,-1] if i==2 else [1,0,-1,1] if branch==0 else [1,-1,-1,0])
            for j,z in enumerate(r):
                ex=[signs[j]]*2
                if i==1 and branch==0 and j==3:ex=[1,-1]
                if i==1 and branch==1 and j==1:ex=[1,-1]
                certify(f'residual {i}.{j}',z,ex)
            certify('active TV '+str(i),sum(z for z,sign in zip(r,signs) if sign>0)-t,[0,0])
            residuals.append(r)
        def terms(expr):
            return [[i,j,str(c)] for (i,j),c in S.Poly(expr,s,t).terms()]
        def rational(expr):
            num,den=S.cancel(expr).as_numer_denom()
            return [terms(num),terms(den)]
        result.append(dict(terms=terms(P),coordinates=[rational(expr) for expr in [u,v,*masses]],degree=int(S.degree(P,t)),events=ids,polynomial=str(P),u=str(u),v=str(v),mass=list(map(str,masses)),signs=checks))
    p,q=[S.sympify(z['polynomial']) for z in result]
    sub=S.subresultants(p,q,t)[-2];a,b=S.Poly(sub,t).all_coeffs()
    value=S.rem(-b*S.invert(a,root.as_expr(),s),root.as_expr(),s)
    assert all(S.rem(numerator(z.subs(t,value)),root.as_expr(),s)==0 for z in (p,q))
    aa,bb=root.refine_root(al,ah,eps=Q(1,2**180));tl,th=interval(S.Poly(value,s),aa,bb);assert T0<tl<th<T1
    def in_field(expr):
        num,den=S.cancel(expr).as_numer_denom()
        mod=root.as_expr()
        small=lambda z:S.rem(z.subs(t,value),mod,s)
        return S.rem(small(num)*S.invert(small(den),mod,s),mod,s)
    slopes=[]
    for f in (p,q):
        val=in_field(-S.diff(f,s)/S.diff(f,t))
        a,b=interval(S.Poly(val,s),aa,bb)
        slopes.append([a,b])
    assert slopes[0][1]<slopes[1][0] or slopes[1][1]<slopes[0][0]
    min_t=S.Poly(S.resultant(root.as_expr(),t-value,s),t).clear_denoms(convert=True)[1].primitive()[1]
    assert min_t.degree()==5 and min_t.is_irreducible and min_t.count_roots(tl,th)==1
    for field in ('u','v'):
        vals=[S.sympify(r[field]).subs(t,value) for r in result]
        assert S.rem(numerator(vals[1]-vals[0]),root.as_expr(),s)==0
    return dict(window=[L,H],transition=dict(polynomial=root.all_coeffs(),interval=[al,ah],radius_in_s=str(value),radius_polynomial=[int(z) for z in min_t.all_coeffs()],slopes=[[float((a+b)/2),str(a),str(b)] for a,b in slopes],radius_bounds=[str(tl),str(th)],s_approx=float((aa+bb)/2),t_approx=float((tl+th)/2)),tube=[T0,T1],other_regions=covers,branches=result)

def cross_sign(expr,P,root,al,ah):
    old=json.loads(Path(__file__).with_name('croisement31.json').read_bytes())
    p,q=map(S.sympify,old['branches']);a,b=S.Poly(S.subresultants(p,q,t)[-2],t).all_coeffs()
    val=S.rem(-b*S.invert(a,root.as_expr(),s),root.as_expr(),s)
    lo,hi=root.refine_root(al,ah,eps=Q(1,2**200))
    def part(f):
        poly=S.Poly(f,s,domain=S.QQ).rem(root)
        if poly.is_zero:return 0
        a,b=interval(poly,lo,hi);assert a*b>0
        return 1 if a>0 else -1
    n,d=S.cancel(expr).as_numer_denom()
    return part(n.subs(t,val))*part(d.subs(t,val))
if __name__=='__main__':print(json.dumps(study(),default=str))
