"""Investigate small trades of a published 6-uniform packing on 58 points."""
import argparse
import ctypes as ct
import itertools
import random
import time
from collections import Counter, defaultdict
from pathlib import Path

ROOT = Path(__file__).resolve().parent
U64 = ct.c_uint64


class Entry(ct.Structure):
    _fields_ = [('word', U64), ('low', U64), ('high', U64)]


def entries(blocks, bound):
    lib = ct.CDLL(str(ROOT / 'trades.dll'))
    lib.enumerate.argtypes = [ct.c_int, ct.c_int, ct.POINTER(U64), ct.c_int, ct.POINTER(Entry), ct.c_int]
    size = 16384
    while True:
        out = (Entry * size)()
        count = lib.enumerate(58, len(blocks), (U64 * len(blocks))(*blocks), bound, out, size)
        assert count >= 0
        if count <= size:
            return [(out[i].word, out[i].low | out[i].high << 64) for i in range(count)]
        size = count


def check(blocks):
    assert all(0 < b < 1 << 58 and b.bit_count() == 6 for b in blocks)
    assert all((a & b).bit_count() <= 1 for a, b in itertools.combinations(blocks, 2))


def compatible_subsets(words, target, start=0, chosen=()):
    if len(chosen) == target:
        yield chosen
        return
    for i in range(start, len(words) - (target - len(chosen)) + 1):
        if all((w & words[i]).bit_count() < 2 for w in chosen):
            yield from compatible_subsets(words, target, i+1, chosen + (words[i],))


def supports(pool, max_size, rng):
    groups = defaultdict(list)
    for word, mask in pool:
        groups[mask].append(word)
    # Include every single candidate support, then a selection of strongly overlapping pairs.
    candidates = set(groups)
    by_index = defaultdict(list)
    for mask in groups:
        for i in positions(mask):
            by_index[i].append(mask)
    for masks in by_index.values():
        if len(masks) > 80:
            masks = rng.sample(masks, 80)
        for a, b in itertools.combinations(masks, 2):
            if (a | b).bit_count() <= max_size:
                candidates.add(a | b)
    return groups, candidates


def positions(mask):
    while mask:
        bit = mask & -mask
        yield bit.bit_length() - 1
        mask ^= bit


def words_within(mask, groups):
    sub, words = mask, []
    while sub:
        words.extend(groups.get(sub, ()))
        sub = (sub-1) & mask
    words.extend(groups.get(0, ()))
    return words


def investigate(blocks, bound, rng, seen):
    pool = entries(blocks, bound)
    groups, boxes = supports(pool, bound, rng)
    neutral = []
    for mask in boxes:
        words = words_within(mask, groups)
        size = mask.bit_count()
        if len(words) < size:
            continue
        old = [b for i,b in enumerate(blocks) if not mask >> i & 1]
        if len(words) > size:
            chosen = next(compatible_subsets(words, size+1), None)
            if chosen:
                return old + list(chosen), pool, len(boxes), True
        if size and len(neutral) < 10000:
            rng.shuffle(words)
            # A point transposition can yield a formally different but isomorphic packing.
            for chosen in itertools.islice(compatible_subsets(words, size), 10):
                new = tuple(sorted(old + list(chosen)))
                if new not in seen:
                    neutral.append(new)
    return rng.choice(neutral) if neutral else None, pool, len(boxes), False


def run():
    parser = argparse.ArgumentParser()
    parser.add_argument('--depth', type=int, default=4)
    parser.add_argument('--iterations', type=int, default=100)
    parser.add_argument('--seed', type=int, default=349545)
    args = parser.parse_args()
    blocks = [int(s,16) for s in (ROOT/'brouwer-58-99.hex').read_text().splitlines()[1:] if s.strip()]
    check(blocks)
    rng = random.Random(args.seed)
    seen = {tuple(sorted(blocks))}
    for i in range(args.iterations):
        start = time.monotonic()
        change, pool, count, improved = investigate(blocks, args.depth, rng, seen)
        hist = sorted(Counter(mask.bit_count() for _,mask in pool).items())
        print(i, 'by conflicts', hist, 'supports tested', count, 'move', change is not None,
              'seconds', round(time.monotonic()-start, 3), flush=True)
        if change is None:
            return
        check(change)
        blocks = list(change)
        seen.add(tuple(sorted(blocks)))
        if improved:
            path = ROOT / ('witness-%d-blocks.hex' % len(blocks))
            path.write_text('$BASE=16\n' + ''.join('%015X\n'%b for b in sorted(blocks)), encoding='ascii')
            print(path, flush=True)
            return


if __name__ == '__main__':
    run()
