"""A weighted one-dimensional contrast bound, attained when the other conditional is shared."""
from fractions import Fraction as F
from itertools import combinations_with_replacement
from pathlib import Path
import json
from rayon26 import Number,witness
from verifier26 import verify

def cell(laws,start):
    ab=[(r[start],sum(r[start:start+2])) for r in laws]
    active=[(a,p) for a,p in ab if p]
    if not active:return F(0),[F(0),F(1)]
    value=max(abs(q*a-p*b)/(q+p) for (a,p),(b,q) in combinations_with_replacement(active,2))
    lo=max([F(0)]+[(a-value)/p for a,p in active]);hi=min([F(1)]+[(a+value)/p for a,p in active])
    assert lo<=hi
    return value,[lo,hi]

def study():
    parent=Path(__file__).parent;cases=[]
    current=json.loads((parent/'relations31.json').read_bytes())
    historical=json.loads((parent/'decouverte30.json').read_bytes())['certificates']
    for name,raw,record in [(r['name'],r['laws'],r.get('certificate')) for r in current]+[(r['name']+'-30',r['laws'],r) for r in historical]:
        laws=[list(map(F,r)) for r in raw];first,second=[cell(laws,k) for k in (0,2)]
        lower=max(first[0],second[0]);common=min(first[0],second[0])==0;cert=None
        if common:
            uv=[Number(z[1][0],0,0) for z in (first,second)]
            cert=dict(feasible=True,witness=witness(laws,lower,*uv));assert verify(laws,lower,cert)
        status='exact' if common else 'lower bound'
        if record:
            if len(record['coeff'])==2 and F(-record['coeff'][1],record['coeff'][0])==lower:status='exact'
            else:assert lower<F(record['endpoints'][1]['e']) and not common
        cases.append(dict(name=name,lower=lower,cell=[first,second],common=common,status=status,witness=cert))
    return cases
if __name__=='__main__':print(json.dumps(study(),default=str))
