"""Exhaustively test every exchange of at most five published blocks.

A six-set not in the seed has a support (the old blocks it conflicts with).
If an exchange removes d old blocks and adds at least d new ones, its union
of supports has size at most d. Restoring unused old blocks only improves it.
"""
from collections import Counter, defaultdict
from itertools import combinations
from local_search import ROOT, check, compatible_subsets, entries, positions, words_within


def submasks(mask, k):
    for subset in combinations(positions(mask), k):
        yield sum(1 << i for i in subset)


def main():
    degree = 5
    seed = [int(s,16) for s in (ROOT/'brouwer-58-99.hex').read_text().splitlines()[1:] if s.strip()]
    check(seed)
    by_support = defaultdict(list)
    for word, mask in entries(seed, degree):
        by_support[mask].append(word)
    by_size = {i: {m for m in by_support if m.bit_count() == i} for i in range(degree+1)}
    assert not any(by_size[i] for i in range(3))
    lookup = {}
    for d in (3,4):
        for k in range(1,d+1):
            ids = defaultdict(list)
            for mask in by_size[d]:
                for key in submasks(mask,k):
                    ids[key].append(mask)
            lookup[d,k] = ids
    unions = {i: set(masks) for i,masks in by_size.items()}
    # Every proper union of size < 5 can be extended by each new support of
    # size 3 or 4 whose overlap is big enough. A size-5 support is already a
    # candidate by itself and cannot belong to any other union of size <= 5.
    for size in (3,4):
        for box in unions[size]:
            for added in (3,4):
                needed = size+added-degree
                for key in submasks(box,needed):
                    for mask in lookup[added,needed].get(key,()):
                        enlarged = box|mask
                        actual = enlarged.bit_count()
                        if actual > size:
                            unions[actual].add(enlarged)
    for d in (3,4,5):
        counts = Counter()
        for box in unions[d]:
            words = words_within(box,by_support)
            counts['max_candidates'] = max(counts['max_candidates'],len(words))
            if len(words) >= d:
                counts['enough_candidates'] += 1
                if next(compatible_subsets(words,d),None):
                    counts['neutral_or_improving'] += 1
                if next(compatible_subsets(words,d+1),None):
                    counts['improving'] += 1
        print(d,'supports',len(by_size[d]),'unions',len(unions[d]),dict(counts),flush=True)


if __name__ == '__main__':
    main()
