"""Minimum derivations with bounded retained lines in the syl/mpd proof DAG."""
import json
from collections import deque
from itertools import combinations

# Given premises are free, with separate immutable contexts for the two outputs.
NAMES=("ax1","ax2","lift","syl_a2i","syl","mpd_a2i","mpd")
PARENTS=((),(),(0,),(1,2),(3,),(1,),(5,))


def run(slots, order):
    if not 1<=slots<=6 or order not in (0,1):
        raise ValueError("unsupported storage or goal order")
    goals=(4,6) if order==0 else (6,4)
    start=(0,0)
    queue=deque([start])
    prior={start:None}
    while queue:
        mask,i=queue.popleft()
        if i==2:
            trail=[]
            node=(mask,i)
            while prior[node]:
                last,line=prior[node]
                trail.append([NAMES[line],[name for j,name in enumerate(NAMES) if node[0]>>j&1]])
                node=last
            return dict(cost=len(trail),states=len(prior),steps=trail[::-1])
        for line,parents in enumerate(PARENTS):
            if mask>>line&1 or not all(mask>>p&1 for p in parents):
                continue
            # A goal can only be produced in its scheduled output position.
            if line in goals and line!=goals[i]:
                continue
            live=[j for j in range(7) if mask>>j&1]
            for kept in combinations(live,min(len(live),slots-1)):
                after=sum(1<<j for j in kept)|(1<<line)
                node=(after,i+(line==goals[i]))
                if node not in prior:
                    prior[node]=((mask,i),line)
                    queue.append(node)
    return dict(cost=None,states=len(prior),steps=[])


def reference():
    from contextes13 import run as logic
    assert logic()['common']==['ax2']
    rows=[]
    for s in range(1,7):
        for order in (0,1):
            row=run(s,order)
            live=set()
            for line,kept in row['steps']:
                assert {NAMES[p] for p in PARENTS[NAMES.index(line)]}<=live
                assert line in kept and set(kept)<=live|{line} and len(kept)<=s
                live=set(kept)
            rows.append([s,order,row['cost']])
    return dict(grid=rows,example=run(2,0))


if __name__=="__main__":
    print(json.dumps(reference(),indent=2))
