"""A delivery-word rule frozen on four outputs, tested on a held-out fifth output."""
from collections import Counter
from itertools import permutations,product,groupby
import json
from motifs21 import solve
from quatre24 import oracle

def predict(motif,word,require_switch=True):
    if word[-1]!='X':return False
    prefix=word[:-1].lstrip('X')
    if require_switch and (len(prefix)<2 or prefix[-1]==prefix[-2]):return False
    runs=''.join(k for k,_ in groupby(prefix))
    return runs in ('AB','BA') or (motif==1 and runs=='BAB')

def study():
    outcomes=[]
    for length in (4,5):
        for motif in (0,1):
            counts=Counter();examples={};labelled=0;initial_errors=[]
            multiplicity=Counter(''.join(perm)
                                 for extra in product('ABX',repeat=length-3) for perm in permutations('ABX'+''.join(extra)))
            for word,weight in sorted(multiplicity.items()):
                parents=[(),(0,) if motif else ()]+[{'A':(0,),'B':(1,),'X':(0,1)}[letter] for letter in word]
                order=tuple(range(2,2+length))
                costs=[oracle(parents,order,f) for f in (False,True)]
                assert costs==[len(solve(parents,order,2,f)) for f in (False,True)]
                predicted=bool(predict(motif,word));gain=costs[1]<costs[0]
                if length==4 and bool(predict(motif,word,False))!=gain:initial_errors.append(word)
                status=('TP' if gain else 'FP') if predicted else ('FN' if gain else 'TN')
                counts[status]+=weight;labelled+=weight
                if status not in examples:examples[status]=dict(word=word,costs=costs)
            if length==4:assert not counts['FP'] and not counts['FN']
            outcomes.append(dict(length=length,motif=motif,counts=dict(counts),examples=examples,words=len(multiplicity),labelled=labelled,initial_errors=initial_errors))
    return outcomes
if __name__=='__main__':print(json.dumps(study()))
