"""Check a bounded proof graph with three rule schemas taken from Metamath set.mm."""
from itertools import product
import json

def run():
    # Each pair denotes implication. The four assumptions of this task are explicit.
    given={('A','T'),('T','B'),('B','C'),('B','D')}
    rules=[]
    def trans(a,b,c):
        ab=(a,b);bc=(b,c);ac=(a,c);lift=(a,bc)
        rules.extend([('syl',(ab,bc),ac),('a1i',(bc,),lift),('mpd',(ab,lift),ac)])
    trans('A','T','B');trans('A','B','C');trans('A','B','D')
    def value(f,bits):
        if isinstance(f,str):return bits[f]
        u,v=f;return not value(u,bits) or value(v,bits)
    for schema,inputs,output in rules:
        if schema=='syl':
            (a,b),(x,c)=inputs;assert x==b and output==(a,c)
        elif schema=='a1i':assert inputs==(output[1],)
        else:
            (a,b),(x,(y,c))=inputs;assert a==x and b==y and output==(a,c)
        for truth in product((False,True),repeat=5):
            bits=dict(zip('ATBCD',truth));assert not all(value(f,bits) for f in inputs) or value(output,bits)
    goals={('A','C'),('A','D')}
    def mincost(wanted):
        candidates=[]
        for mask in range(1<<len(rules)):
            known=set(given);cost=0
            for i,(s,ins,out) in enumerate(rules):
                if mask>>i&1:
                    if not set(ins)<=known:break
                    known.add(out);cost+=2
            else:
                if wanted<=known:candidates.append((cost,mask))
        return min(candidates)
    c,mask=mincost(goals);separate=sum(mincost({g})[0] for g in goals)
    # Independent closure for the winning subgraph. Every cited page supplies two
    # non-hypothesis steps when its own named dependencies are treated as available.
    known=set(given);todo=[r for i,r in enumerate(rules) if (mask>>i)&1]
    while todo:
        row=next(r for r in todo if set(r[1])<=known);known.add(row[2]);todo.remove(row)
    assert goals<=known
    return dict(instances=len(rules),subsets=2**len(rules),truth_assignments=32,shared_cost=c,separate_cost=separate,winner=[i for i in range(len(rules)) if mask>>i&1])
if __name__=='__main__':print(json.dumps(run(),indent=2))
