"""Compose optimal block costs through one surviving premise; verify by joint BFS."""
from collections import deque
from functools import lru_cache
from pathlib import Path
from itertools import product
from barriere30 import bfs
import json
@lru_cache(None)
def costs(word,motif,cap,start):
    parents=[0,motif]+[{'A':1,'B':2,'X':3}[c] for c in word]
    n=len(word);q=deque([(start,0,0,0)]);seen=set();ends={}
    while q:
        live,i,spent,dist=q.popleft()
        if (live,i,spent) in seen:continue
        seen.add((live,i,spent))
        if i==n:
            for h in (0,1,2):
                if live&h==h:ends.setdefault(h,dist)
            continue
        for v,ps in enumerate(parents):
            if 2<=v<i+2 or live>>v&1 or live&ps!=ps:continue
            used=spent+(v>i+2)
            if used>cap:continue
            for w in [0]+[1<<j for j in range(len(parents)) if live>>j&1]:
                m=w|1<<v;j=i
                while j<n and m>>(j+2)&1:m^=1<<(j+2);j+=1
                q.append((m,j,used,dist+1))
    return ends
def study():
    old=json.loads(Path(__file__).with_name('barriere30.json').read_bytes());out=[]
    for r in old:
        m=r['motif'];rows=[]
        for z in r['cases']:
            a,b=z['a'],z['b'];vals=[];opts=[]
            for k in (0,1,2,len(a+b)):
                choices=[(cost+costs(b,m,k-i,h)[0],h,i) for i in range(k+1) for h,cost in costs(a,m,i,0).items()]
                value,h,i=min(choices);assert value==bfs(a,b,m,k,True)
                vals.append(value);opts.append([h,i])
            rows.append(dict(a=a,b=b,reset=z['costs'],one=vals,interface=opts))
        out.append(dict(motif=m,cases=rows))
    return out
if __name__=='__main__':print(json.dumps(study()))
