"""Shortest delivery traces with exactly one out-of-order construction."""
from collections import deque
from itertools import product
from quatre24 import oracle
import json

def limited(word,motif):
    order=tuple(range(2,len(word)+2))
    parents=[0,int(bool(motif))]+[{'A':1,'B':2,'X':3}[z] for z in word]
    first=(0,0,False);prev={first:None};queue=deque([first])
    while queue:
        state=mask,i,spent=queue.popleft()
        if i==len(word):
            if not spent:continue
            trace=[]
            while prev[state] is not None:
                parent,line,early=prev[state];trace.append(dict(before=parent[:2],line=line,early=early,after=state[:2]));state=parent
            return trace[::-1]
        for line,ps in enumerate(parents):
            bit=1<<line;early=line in order[i+1:]
            if mask&bit or mask&ps!=ps or line in order[:i] or spent and early:continue
            for keep in [0]+[1<<v for v in range(len(parents)) if mask>>v&1]:
                held=keep|bit;j=i
                while j<len(word) and held&(1<<order[j]):
                    held^=1<<order[j];j+=1
                nxt=(held,j,spent or early)
                if nxt not in prev:
                    prev[nxt]=state,line,early;queue.append(nxt)

def study():
    rows=[];examples=[]
    for motif in (0,1):
        num=gains=missed=full=0;first=None
        for chars in product('ABX',repeat=5):
            if len(set(chars))<3:continue
            word=''.join(chars)
            ps=[(),(0,) if motif else ()]+[{'A':(0,),'B':(1,),'X':(0,1)}[z] for z in chars]
            costs=[oracle(ps,tuple(range(2,7)),flag) for flag in (False,True)]
            path=limited(word,motif);one=len(path) if path else None
            achievable=min([costs[0]]+([one] if one is not None else []))
            num+=1;gains+=costs[1]<costs[0];missed+=achievable>costs[1];full+=achievable<costs[0]
            case=dict(word=word,motif=motif,costs=costs,one=one,trace=path)
            if achievable>costs[1] and first is None:first=case
            if word in ('ABABX','BBABX'):examples.append(case)
        rows.append(dict(motif=motif,distinct=num,gains=gains,one_gains=full,suboptimal=missed,first=first))
    return dict(rows=rows,examples=examples)
if __name__=='__main__':print(json.dumps(study()))
