"""Exact optimal TV radius for the strictly positive triple. Requires SymPy."""
import json
from fractions import Fraction as F
from itertools import product
from pathlib import Path
import sympy as S
from contacts27 import TRIPLE
from rayon26 import clip,constraints
from verifier26 import BOX,permitted,vertices

e,v=S.symbols('e v')
R=S.Rational
P=S.Poly(63011844*e**5-42507990*e**4-10698219*e**3+8543892*e**2+316157*e-257528,e,domain=S.QQ)
L,H=R(19133549021646,10**14),R(19133549021648,10**14)

def interval(poly,left,right):
    lo=hi=R(0)
    for c in poly.all_coeffs():
        products=[a*b for a in (lo,hi) for b in (left,right)]
        lo=min(products)+c;hi=max(products)+c
    return lo,hi

def sign_at_root(expr):
    num,den=S.cancel(expr).as_numer_denom()
    def sign(part):
        poly=S.Poly(part,e,domain=S.QQ).rem(P)
        if poly.is_zero:return 0
        left,right=L,H
        for _ in range(160):
            a,b=interval(poly,left,right)
            if a>0:return 1
            if b<0:return -1
            mid=(left+right)/2
            if P.eval(left)*P.eval(mid)<0:right=mid
            else:left=mid
        raise ArithmeticError('Could not separate a nonzero value')
    a,b=sign(num),sign(den)
    assert b
    return a*b

def study():
    if not __debug__:raise RuntimeError('Run without -O')
    assert P.count_roots(L,H)==1 and P.eval(L)*P.eval(H)<0
    assert S.Poly(P.as_expr(),e,modulus=31).degree()==5 and S.Poly(P.as_expr(),e,modulus=31).is_irreducible
    a1,a3,b1,b4,c2,c4=map(R,('1/3','7/27','1/21','4/21','3/14','4/7'))
    A=(a1-e)*v/(v-a3)
    B=(b1+e)*(1-v)/(1-v-b4)
    C=1-c2*(1-v)/(1-v-c4+e)
    f,g=[S.cancel(A-z).as_numer_denom()[0] for z in (B,C)]
    factors=S.factor_list(S.resultant(f,g,v))[1]
    assert any(S.Poly(z,e).monic()==P.monic() for z,k in factors)
    vv=(6174*e**2-2205*e-511)/(47628*e**3-3906*e**2-11637*e+389)
    u=S.cancel(A.subs(v,vv))
    for bound in (B,C):assert sign_at_root(u-bound.subs(v,vv))==0
    assert all(sign_at_root(x)>0 for x in (e,a1-e,c4-e-b4,vv-a3,1-vv-c4+e,vv-u,1-vv-u))
    assert sign_at_root(S.diff(A-C,v).subs(v,vv))==1
    masses=[1-a3/vv,1-b4/(1-vv),c2/(1-u)]
    assert all(sign_at_root(x)>0 and sign_at_root(1-x)>0 for x in [u,vv,*masses])
    active=[]
    for m,row in zip(masses,TRIPLE):
        image=[m*u,m*(1-u),(1-m)*vv,(1-m)*(1-vv)]
        errors=[S.cancel(x-R(y)) for x,y in zip(image,row)]
        signs=[sign_at_root(z) for z in errors]
        # The event made of the positive residual coordinates maximizes TV.
        assert sign_at_root(sum(z for z,s in zip(errors,signs) if s>0)-e)==0
        active.append(signs)
    high=F(3135,16384)
    assert H<R(high)
    region_planes=[]
    for region in range(3):
        _,used=clip(constraints(TRIPLE,high,region))
        assert set(used)<=permitted(TRIPLE,high,region) and not vertices([*BOX,*used])
        region_planes.append(used)
    # Three active planes in the lifted coordinates. Their Cramer numerators
    # independently give the optimal-value polynomial by imposing w=u*v.
    M=S.Matrix([[-a3,e-a1,1],[b4-1,-b1-e,1],[c4-e-1,c2-1,1]])
    rhs=S.Matrix([0,-b1-e,c2+c4-e-1]);det=S.factor(M.det())
    nums=[]
    for i in range(3):
        T=M.copy();T[:,i]=rhs;nums.append(S.factor(T.det()))
    assert sign_at_root(det)!=0
    gap=S.factor(nums[2]*det-nums[0]*nums[1]);ratio=S.cancel(gap/P.as_expr())
    assert ratio.is_Rational and ratio!=0
    assert sign_at_root(nums[0]/det-u)==0 and sign_at_root(nums[1]/det-vv)==0
    approx=lambda expr:float(expr.subs(e,(L+H)/2))
    return dict(polynomial=[int(x) for x in P.all_coeffs()],isolation=[str(L),str(H)],
                prime=31,cramer=dict(det=str(det),numerators=list(map(str,nums)),factor=str(ratio)),v=str(vv),u=str(u),masses=[str(S.cancel(m)) for m in masses],
                decoded=[approx(x) for x in [u,vv,*masses]],signs=active,
                upper=str(high),excluded_planes=region_planes,resultant=str(S.factor(S.resultant(f,g,v))))
if __name__=='__main__':print(json.dumps(study()))
