"""Check a finite wheel proof with explicit facts and independently cost its DAG."""
from collections import Counter
from fractions import Fraction as F
from itertools import permutations,combinations
from math import gcd
import json


def rank(labels,index):
    ring=sorted(index,key=labels.__getitem__)
    value=0
    for step,x in enumerate(index):
        j=ring.index(x)
        if step:value=value*len(ring)+j
        ring=ring[j+1:]+ring[:j]
    return value


def counts(source,pin):
    outer=(2,3,4,5,6,7)
    h=[0]*5;d=[0]*5;t=[0]*5
    labels=([0,*s] for s in permutations(range(1,8))) if pin else permutations(range(8))
    for seq in labels:
        a=rank(seq,outer);b=rank(seq,source)
        if gcd(a,6)==1:
            r=a%5;t[r]+=1
            h[r]+=int(gcd(b,6)==1);d[r]+=int(b in (2,3))
    return h,d,t


# One reusable numerical table supports both endpoints of the requested certificate.
RULES=(('table',('case',),4),('mass',('table',),1),('double_reject',('table',),1),
       ('deficit',('mass','double_reject','reflection'),1),('local',('mass','table'),1),
       ('global',('local','uniform'),1),('goal',('global','deficit'),1))
BASE={'case','reflection','uniform'}


def verify(source,weights):
    if not set(source).isdisjoint((6,7)): raise ValueError('reflection')
    h,d,t=counts(source,True)
    assert len(set(t))==1 and all(h[r]+h[-r]==t[r]-d[r] for r in range(5))
    if len(weights)!=5 or min(weights)<=0 or len(set(weights))!=1: raise ValueError('uniform')
    if sum(h)<=0: raise ValueError('mass')
    delta=(F(d[0])-F(sum(d),5))/(2*sum(h))
    assert F(1,5)-F(h[0],sum(h))==delta
    hg,dg,tg=counts(source,False)
    assert [x*y for x,y in zip(h,weights)]==hg and sum(hg)==8*sum(h)
    return str(delta),str(F(hg[0],sum(hg)))


def costs():
    dist={s:0 for s in BASE}; known=set(BASE);plan=[]
    for name,needs,w in RULES:
        assert set(needs)<=known
        dist[name]=w+sum(dist[s] for s in needs)
        known.add(name);plan.append(name)
    subsets=[]
    for n in range(len(RULES)+1):
        for subset in combinations(RULES,n):
            facts=set(BASE);price=0
            for name,needs,w in subset:
                if set(needs)<=facts: facts.add(name);price+=w
            if 'goal' in facts: subsets.append(price)
    return dict(tree=dist['goal'],shared=min(subsets),certificate=plan,subsets=2**len(RULES))


def experiment():
    src=(3,2,1,0)
    values=verify(src,[8]*5);refused=[]
    for s,w in [(src,[2,1,1,1,1]),((6,2,1,0),[8]*5)]:
        try: verify(s,w)
        except ValueError as exc: refused.append(str(exc))
    assert refused==['uniform','reflection'] and values==('1/140','27/140')
    return dict(values=values,costs=costs(),rejected=refused,full_permutations=40320)


if __name__=='__main__': print(json.dumps(experiment(),indent=2))
