"""Exact replay of the published matrices and their independently obtained dual certificates."""
from fractions import Fraction as F
from pathlib import Path
from itertools import combinations_with_replacement
import json
from transport24 import decode, nearest_image, transport
from verifier21 import table, check

def event_error(q,x):
    return max(sum((q[i]-x[i] for i in range(len(q)) if mask>>i&1),F(0)) for mask in range(1<<len(q)))

def image(a,k):
    return [sum(s*t for s,t in zip(a,col)) for col in zip(*k)]

def fixed_small():
    laws=[]
    for i,j in combinations_with_replacement(range(3),2):
        laws.append([F(int(k==i)+int(k==j),2) for k in range(3)])
    # Directly evaluate the upper boundary of the source testing polygon at target prefixes.
    def ordinate(a,b,u):
        total=sum(x for x,z in zip(a,b) if not z)
        for ratio,z in sorted(((x/z,z) for x,z in zip(a,b) if z),reverse=True):
            amount=min(z,u);total+=ratio*amount;u-=amount
        return total
    checked=0
    for a in laws:
        for b in laws:
            for q in laws:
                for y in laws:
                    x=nearest_image(a,b,q,y);k=transport(a,b,x,y)
                    assert image(a,k)==x and image(b,k)==y
                    vertical=max(sum(q[i] for i in range(3) if mask>>i&1)-
                                 ordinate(a,b,sum(y[i] for i in range(3) if mask>>i&1)) for mask in range(8))
                    assert vertical==event_error(q,x);checked+=1
    return checked

def variable_lower_bound():
    """Prove the published lower endpoint by testing all 16 output events."""
    data=json.loads(Path(__file__).with_name('marges24.json').read_bytes())['flexible']
    lower=F(data['history'][-1]['lower'])
    targets=table(data['target'])
    indicators=[[(mask>>i)&1 for i in range(4)] for mask in range(16)]
    events=[[sum(x*k for x,k in zip(row,flags)) for flags in indicators] for row in targets]
    def strictly_feasible(u,v,radius):
        first=[u*h[0]+(1-u)*h[1] for h in indicators]
        second=[v*h[2]+(1-v)*h[3] for h in indicators]
        for desired in events:
            lo,hi=F(0),F(1)
            for f,s,t in zip(first,second,desired):
                # m*(f-s)+s-t < radius for every event, with 0<=m<=1.
                rhs=radius+t-s
                if f>s:hi=min(hi,rhs/(f-s))
                elif f<s:lo=max(lo,rhs/(f-s))
                elif rhs<=0:return False
            if lo>=hi:return False
        return True
    todo=[(F(0),F(0),F(1),0)];checked=0
    while todo:
        u,v,w,level=todo.pop();half=w/2;checked+=1
        if strictly_feasible(u+half,v+half,lower+half):
            assert level<24
            todo.extend((u+du,v+dv,half,level+1) for du in (0,half) for dv in (0,half))
    e,u,v=map(F,data['best'][:3])
    err=[event_error(row,[m*u,m*(1-u),(1-m)*v,(1-m)*(1-v)])
         for row,m in zip(targets,map(F,data['best'][3]))]
    assert max(err)==e and e==F(19,100)
    return checked

def verify():
    d=json.loads(Path(__file__).with_name('jeu24.json').read_bytes())
    for r in d['anchored']:
        s,t=table(r['source']),table(r['target']);z=decode(*s[:2],*t)
        assert z['kernel']==table(r['construction']['kernel'])
        err=[event_error(law,image(m,z['kernel'])) for law,m in zip(t,s)]
        assert max(err)==check(s,t,r['baseline'])
    for r in d['perturbations']+d['merges']:
        check(table(r['source']),table(r['target']),r.get('certificate') or r['free'])
    return dict(anchored=len(d['anchored']),other=len(d['perturbations'])+len(d['merges']),
                fixed_grid=fixed_small(),variable_boxes=variable_lower_bound())

if __name__=='__main__':print(json.dumps(verify()))
