"""Exact TV approximation by two shared binary conditionals, plus two related controls."""
from fractions import Fraction as F
from itertools import combinations_with_replacement, permutations, product
from pathlib import Path
import json
from marges24 import best_mass
from jeu24 import faithful, load, table
from deficience21 import certificate, push, tv
from transport24 import decode

TARGET=table([['5/24','1/24',0,'3/4'],['3/4',0,'1/4',0],['5/8','1/8',0,'1/4']])

def law(u,v,m):
    return [m*u,m*(1-u),(1-m)*v,(1-m)*(1-v)]


def family(a,p,c):
    a,p,c=map(F,(a,p,c))
    if not 0<=a<p<1 or not 0<=c<=1-a:raise ValueError('invalid target probabilities')
    e=(1-p)*(1-a)/(2-a-p)
    if c>e or 1-a-c<=2*e:raise ValueError('outside proved sufficient conditions')
    v=e/(1-a)
    targets=[[a,c,F(0),1-a-c],[p,F(0),1-p,F(0)]]
    images=[law(F(1),v,m) for m in (a,p)]
    assert all(tv(left,right)==e for left,right in zip(targets,images))
    return e,v


def profile():
    a,c,_,_=TARGET[0];p=TARGET[1][0];e,v=family(a,p,c)
    rows=[best_mass(row,F(1),v) for row in TARGET]
    s=[[sum(row[:2]),sum(row[2:])] for row in TARGET]
    free=certificate(s,TARGET);kept=faithful(s,TARGET)
    assert TARGET==table(load('commun23')['controls'][1]['target'])
    assert free['value']==kept['value']==F(19,96) and max(val for val,m in rows)==e
    syms=[]
    for swap,i,j in product(range(2),repeat=3):
        order=[i,1-i,2+j,3-j]
        if swap:order=order[2:]+order[:2]
        if sorted(tuple(row[k] for k in order) for row in TARGET)==sorted(map(tuple,TARGET)):syms.append(order)
    assert len(syms)==1
    cases=0
    for A,P,C in product(range(9),repeat=3):
        try:family(F(A,8),F(P,8),F(C,8))
        except ValueError:continue
        cases+=1
    return dict(target=TARGET,source=s,u=F(1),v=v,value=e,masses=[m for _,m in rows],
                errors=[val for val,_ in rows],free=free,faithful=kept,symmetries=syms,family_grid=cases)


def centre(laws):
    laws=[list(map(F,row)) for row in laws]
    if not laws or any(len(row)!=3 or min(row)<0 or sum(row)!=1 for row in laws):
        raise ValueError('expected a nonempty family of ternary probability laws')
    high=list(map(max,zip(*laws)));low=list(map(min,zip(*laws)))
    bounds=[max(u-l for u,l in zip(high,low))/2,(1-sum(low))/3]
    bounds += [(sum(x*f for x,f in zip(high,flags))-1)/sum(flags)
               for flags in product((0,1),repeat=3) if any(flags)]
    e=max(bounds)
    z=[max(F(0),u-e) for u in high]
    for i,l in enumerate(low):z[i]+=min(1-sum(z),l+e-z[i])
    assert sum(z)==1 and max(tv(z,r) for r in laws)==e
    return e,z,bounds[0]


def ternary():
    groups=[];examples=[]
    for n in (3,6):
        laws=[[F(i,n),F(j,n),F(n-i-j,n)] for i in range(n+1) for j in range(n-i+1)]
        count=loss=interior=0
        for rows in combinations_with_replacement(laws,3):
            e,z,pair=centre(rows);count+=1
            if e>pair:
                loss+=1
                if min(map(min,rows))>0:
                    if not interior:examples.append(dict(rows=rows,value=e,centre=z,pair=pair))
                    interior+=1
        groups.append(dict(den=n,count=count,gaps=loss,interior_gaps=interior))
    return dict(groups=groups,examples=examples)


def reader():
    rows=[];w=F(9,10)**10;slope=F(70,27)*w
    for h in [F(0)]+[F(1,10*2**k) for k in (1,2,3,4,5,6,7,8,9,10)]:
        a=((F(9,10)+h)*F(44,45)*F(14,15))**10;b=F(70,27)*h
        t=[[a*w,a*(1-w),F(0),1-a],[F(0),b,F(0),1-b],[b*w,b*(1-w),F(0),1-b]]
        ans=decode([a,1-a],[b,1-b],*t);e=a*b*w/(a+b)
        k=[[a*w/(a+b),1-a*w/(a+b),F(0),F(0)],[F(0),F(0),F(0),F(1)]]
        assert ans['value']==e==max(tv(push(row,k),q) for row,q in zip([[a,1-a],[b,1-b],[b,1-b]],t))
        rows.append(dict(h=h,value=e,kernel=k,ratio=e/h if h else None))
    return dict(slope=slope,rows=rows)


if __name__=='__main__':
    print(json.dumps(dict(profile=profile(),ternary=ternary(),reader=reader()),default=str))
