"""Early proof construction across an explicit empty-memory and availability barrier."""
from pathlib import Path
from collections import deque
from functools import lru_cache
from itertools import product
import json
from deux27 import limited

def bfs(a,b,motif,cap,keep_one=False):
    word=a+b;cut=len(a);n=len(word)
    ps=[0,motif]+[{'A':1,'B':2,'X':3}[x] for x in word]
    q=deque([(0,0,0,0)]);seen=set()
    while q:
        mask,i,used,cost=q.popleft()
        if i==n:return cost
        state=mask,i,used
        if state in seen:continue
        seen.add(state);end=cut if i<cut else n
        for v in [0,1,*range(i+2,end+2)]:
            if mask>>v&1 or mask&ps[v]!=ps[v]:continue
            spent=used+(v>i+2)
            if spent>cap:continue
            for keep in [0]+[1<<w for w in range(n+2) if mask>>w&1]:
                m=keep|1<<v;j=i
                while j<end and m>>(j+2)&1:m^=1<<(j+2);j+=1
                if i<cut and j==cut:
                    m=(m&3) if keep_one else 0
                    assert m.bit_count()<=1
                q.append((m,j,spent,cost+1))

def study():
    data=json.loads(Path(__file__).with_name('blocs29.json').read_bytes());out=[]
    bounded=lru_cache(None)(limited)
    for block in data:
        m=block['motif'];result=[]
        for a,b in product(block['blocks'],repeat=2):
            cap=len(a+b)*2
            costs=[min(bounded(a,m,i)+bounded(b,m,k-i) for i in range(k+1)) for k in range(3)]
            free=bounded(a,m,len(a)*2)+bounded(b,m,len(b)*2)
            assert [*costs,free]==[bfs(a,b,m,k) for k in (0,1,2,cap)]
            result.append(dict(a=a,b=b,costs=[*costs,free]))
        out.append(dict(motif=m,cases=result))
    return out
if __name__=='__main__':print(json.dumps(study()))
