"""Irredundant rejection covers and active contacts around the four critical radii."""
import json
from fractions import Fraction as F
from itertools import combinations
from pathlib import Path
from rayon26 import CUBE,clip,constraints,coords,decide,extremes
from verifier26 import permitted,verify,vertices,BOX

TRIPLE=[[F(k,n) for k in w] for n,w in [(27,(9,5,7,6)),(21,(1,9,7,4)),(14,(1,3,2,8))]]

def interval(planes):
    vs,_=clip(planes)
    return [x[0] for x in extremes(vs)] if vs else None

def excludes(bounds):
    return bounds is None or bounds[0]>0 or bounds[1]<0

def compact(rows,e,j):
    _,original=clip(constraints(rows,e,j));planes=list(original)
    for h in reversed(original):
        trial=[p for p in planes if p!=h]
        if excludes(interval(trial)):planes=trial
    span=interval(planes)
    assert excludes(span)
    assert all(not excludes(interval([p for p in planes if p!=h])) for h in planes)
    base=permitted([],e,j)
    keys=[permitted([row],e,j) for row in rows]
    owners=[('domain' if p in base else ''.join(chr(65+i) for i,one in enumerate(keys) if p in one)) for p in planes]
    assert all(owners)
    return dict(initial=len(original),planes=planes,range=span,owners=owners)

def contact(rows,e,j):
    planes=constraints(rows,e,j);vs,_=clip(planes)
    if not vs:return None
    values=extremes(vs)
    val,p=min(values,key=lambda z:abs(z[0]))
    active=[h for h in [*CUBE,*planes] if sum(a*b for a,b in zip(h[:3],p))+h[3]==0]
    labels=[['domain' if h in CUBE or h in permitted([],e,j) else ''.join(chr(65+i) for i,r in enumerate(rows) if h in permitted([r],e,j)) ,h] for h in active]
    return dict(kind='vertex' if p in list(map(coords,vs)) else 'chord',gap=val,point=p,planes=labels)

def study():
    old=json.loads(Path(__file__).with_name('robuste26.json').read_bytes())
    fixed=F(3,16);parts=[compact(TRIPLE,fixed,j) for j in range(4)]
    assert not verify(TRIPLE,fixed,dict(feasible=False,cover=parts))
    high=F(3135,16384);other=[compact(TRIPLE,high,j) for j in range(3)]
    for part in other:
        # The reduced cover may still contain vertices; verifier checks all four
        # regions together at 3/16, and the critical-value checker handles these.
        assert excludes(part['range'])
    brackets=[]
    for rows,rec in zip([TRIPLE,*combinations(TRIPLE,2)],[old['full'],*old['pairs']]):
        lo,hi=map(F,rec['interval']);stages=[]
        for level in range(21):
            if level in (0,20):
                stages.append([dict(e=e,regions=[contact(rows,e,j) for j in range(4)]) for e in (lo,hi)])
            if level<20:
                mid=(lo+hi)/2
                if decide(rows,mid)['feasible']:hi=mid
                else:lo=mid
        brackets.append(stages)
    return dict(laws=TRIPLE,e=fixed,cover=parts,upper=high,other=other,contacts=brackets)

if __name__=='__main__':print(json.dumps(study(),default=str))
