"""Three proof blocks, exact dynamic composition and independent joint breadth-first search."""
from collections import deque
from itertools import product
from functools import lru_cache
from pathlib import Path
from interface31 import costs
import json
def joint(blocks,motif,k,retain):
    word=''.join(blocks);ends=[sum(map(len,blocks[:i+1])) for i in range(len(blocks))]
    parents=[0,motif]+[{'A':1,'B':2,'X':3}[x] for x in word];q=deque([(0,0,0,0)]);seen=set()
    while q:
        live,i,spent,d=q.popleft()
        if i==len(word):return d
        if (live,i,spent) in seen:continue
        seen.add((live,i,spent));stop=next(z for z in ends if z>i)
        for v in (0,1,*range(i+2,stop+2)):
            if live>>v&1 or live&parents[v]!=parents[v]:continue
            nxt=spent+int(v>i+2)
            if nxt>k:continue
            for keep in [0]+[1<<j for j in range(len(parents)) if live>>j&1]:
                m=keep|1<<v;j=i
                while j<stop and m>>(j+2)&1:m^=1<<(j+2);j+=1
                if j==stop:m=(m&3) if retain else 0
                q.append((m,j,nxt,d+1))
def study():
    old=json.loads(Path(__file__).with_name('blocs29.json').read_bytes());out=[]
    for r in old:
        motif=r['motif'];words=r['blocks']
        for bs in product(words,repeat=3):
            @lru_cache(None)
            def comp(i,h,k,retain):
                if i==3:return 0
                return min(val+comp(i+1,end,k-j,retain) for j in range(min(k,len(bs[i]))+1) for end,val in costs(bs[i],motif,j,h).items() if retain or end==0)
            budgets=(0,1,2,3,sum(map(len,bs)))
            vals=[[comp(0,0,k,retain) for k in budgets] for retain in (False,True)]
            # Joint replay of both modes at budgets relevant to the first saturation.
            for k in (0,1,2):
                for mode in (0,1):assert vals[mode][k]==joint(bs,motif,k,mode)
            out.append(dict(motif=motif,blocks=bs,reset=vals[0],one=vals[1]))
    return out
if __name__=='__main__':print(json.dumps(study()))
