"""Two loss dates, including the boundary where the exclusive model always fires."""
from fractions import Fraction as F
from math import comb,prod
from deficience21 import certificate,tv
from verifier21 import check
from cellules22 import experiment,preserving
from commun23 import solve
import json


def study():
    rates=[F(1,10),F(1,45),F(1,15),F(1,10)]
    rows=[]
    for n in (6,8,10):
        assert max(n*x for x in rates)<=1
        survival=prod(1-r for r in rates[:3])
        joint=[]
        for exclusive in (False,True):
            states={(0,False):F(1)}
            for step,rate in enumerate(rates):
                nxt={}
                for (dead,first),mass in states.items():
                    m=n-dead
                    weights=([1-m*rate,m*rate] if m else [F(1)]) if exclusive else [comb(m,k)*rate**k*(1-rate)**(m-k) for k in range(m+1)]
                    for k,w in enumerate(weights):
                        if not w:continue
                        key=(dead+k,first or (step<3 and k>0)) if step<3 else (int(k>0),first)
                        nxt[key]=nxt.get(key,F(0))+mass*w
                states=nxt
            table=[states.get((j,bool(y)),F(0)) for y in range(2) for j in range(2)]
            y0=prod(1-n*r for r in rates[:3]) if exclusive else survival**n
            j0=1-n*survival*rates[3] if exclusive else (1-survival*rates[3])**n
            both=y0*((1-n*rates[3]) if exclusive else (1-rates[3])**n)
            assert table==[both,y0-both,j0-both,1-y0-j0+both]
            joint.append(table)
        for rounded in (False,True):
            def parts(law):
                a=[sum(law[:2]),sum(law[2:])]
                cond=[([x/m for x in law[2*i:2*i+2]] if m else [F(1),F(0)]) for i,m in enumerate(a)]
                if rounded:cond[1]=[F(0),F(1)]
                return a,cond
            a,u=parts(joint[0]);b,v=parts(joint[1]);s,t=experiment(a,b,u,v)
            z=solve(a,b,*t);cert=certificate(s,t)
            assert check(s,t,cert)==z['value']
            if min(b)>0:keep=preserving(a,b,u,v)['keep']
            else:
                # Only Q charges cell zero. Use u there, and the midpoint in the other cell.
                assert b==[0,1]
                keep=tv(u[1],v[1])/2
            rows.append(dict(n=n,rounded=rounded,source=s,target=t,keep=keep,certificate=cert,construction=z))
    return rows
if __name__=='__main__':print(json.dumps(study(),default=str))
