"""Check all hosts, labels and coverage. No downloads or search code needed."""
import gzip
from itertools import combinations, permutations, product
from math import factorial
from pathlib import Path

def matrix(n, word):
    assert len(word) == n*(n-1)//2 and set(word) <= {'0','1'}
    a = [[0]*n for _ in range(n)]
    for bit, (i,j) in zip(word, combinations(range(n),2)):
        a[i][j] = int(bit)
        a[j][i] = 1-int(bit)
    return a

def canonical(a):
    # These vertex signatures are preserved by every isomorphism.
    d = list(map(sum, a))
    signature = [tuple(sum(row[j] for j in range(8) if d[j]==k)
                       for k in range(8)) for row in a]
    groups = [[i for i,t in enumerate(signature) if t==s]
              for s in sorted(set(signature))]
    best = None
    for blocks in product(*(permutations(g) for g in groups)):
        p = sum(blocks, ())
        word = bytes(a[i][j] for i,j in combinations(p,2))
        if best is None or word < best:
            best,count = word,0
        count += (word==best)
    return best,count

def check():
    seen=set();pop=same=sinks=0
    with gzip.open(Path(__file__).resolve().parents[1]/'results/pack.txt.gz','rt') as fh:
        for row in fh:
            core,host,*labels = row.split()
            a,g = matrix(8,core),matrix(17,host)
            assert list(map(sum,g))==[8]*17
            second=list(map(int,labels));first=list(range(9))
            assert len(second)==len(set(second))==9 and set(second)<=set(range(17))
            assert second!=first
            for f in [first,second]:
                assert all(g[f[8]][f[i]] for i in range(8))
                assert all(g[f[i]][f[j]]==a[i][j] for i,j in combinations(range(8),2))
            key,aut=canonical(a)
            assert key not in seen and factorial(8)%aut==0
            seen.add(key);pop+=factorial(8)//aut
            sinks+=any(sum(r)==0 for r in a)
            if first[8]==second[8]:
                same+=1
                exception = [[int((i<5<=j) or (i<5 and j<5 and (j-i)%5 in (1,2))
                                      or (i>=5 and j>=5 and (j-i)%3==1))
                                  for j in range(8)] for i in range(8)]
                assert key==canonical(exception)[0]
    assert pop==2**28
    print(f'{len(seen)} distinct cores; orbits cover {pop} labelled tournaments.')
    print(f'{len(seen)-same} pairs of distinct roots, {same} same root.')
    print(f'{2*len(seen)-sinks} source-or-sink nine-vertex types (intersection {sinks}).')

if __name__=='__main__': check()
