"""Order-preserving graph isomorphisms on the five-line witnesses."""
from itertools import permutations
from collections import Counter
import json
from pathlib import Path
from motifs21 import solve


def canonical(masks,order):
    codes=[]
    for a,b in permutations(range(2)):
        seq=[a,b,*order]
        codes.append(tuple(sum(1<<k for k,j in enumerate(seq) if masks[i]>>j&1) for i in seq))
    return min(codes)


def study():
    data=json.loads(Path(__file__).with_name('trois22.json').read_bytes())
    rows=[r for r in data if r['n']==5 and r['cap']==2];classes={}
    for r in rows:
        code=canonical(r['masks'],r['order'])
        cls=classes.setdefault(code,dict(count=0,strict=r['strict'],early=r['early'],example=r))
        assert (r['strict'],r['early'])==(cls['strict'],cls['early'])
        cls['count']+=1
    gains=[]
    for code,row in sorted(classes.items()):
        if row['early']>=row['strict']:continue
        r=row['example'];parents=[tuple(j for j in range(2) if mask>>j&1) for mask in r['masks']]
        gains.append(dict(code=code,**row,traces=[solve(parents,r['order'],2,f) for f in (False,True)]))
    return dict(all_classes=len(classes),labelled=len(rows),gains=gains)
if __name__=='__main__':print(json.dumps(study()))
