"""Exact finite checks for the bit-reversal construction."""

from collections import defaultdict
from fractions import Fraction
from functools import cache
from math import factorial


def run_length(word):
    return next(i for i, bit in enumerate(word) if bit != word[0])


def verify_width(width):
    size = 1 << width
    across = set()
    down = set()
    groups = defaultdict(list)

    for index in range(2 * size):
        word = f"{index:0{width + 1}b}"
        source = word[1:]
        target = word[:-1]
        if source == target:
            continue
        row = int(source[::-1], 2)
        col = int(target, 2)
        row_black = int(source, 2)
        col_black = int(target[::-1], 2)
        horizontal_side = int(col > row_black)
        vertical_side = int(row > col_black)
        assert col != row_black and row != col_black
        assert horizontal_side == int(word[0]) and vertical_side == int(word[-1])
        assert (row, horizontal_side) not in across
        assert (col, vertical_side) not in down
        across.add((row, horizontal_side))
        down.add((col, vertical_side))
        signature = (horizontal_side, vertical_side, run_length(word), run_length(word[::-1]))
        groups[signature].append((row, col, row_black, col_black))

    inverse = [int(f"{i:0{width}b}"[::-1], 2) for i in range(size)]
    expected = {(i, side) for i, split in enumerate(inverse)
                for side in (0, 1) if split != (size - 1) * side}
    assert across == down == expected

    for (horizontal_side, vertical_side, _, _), cells in groups.items():
        rows, cols, row_blacks, col_blacks = zip(*cells)
        # Compare the worst possible pair of each endpoint type in the group.
        if horizontal_side == 0:
            assert max(cols) < min(row_blacks)
        else:
            assert min(cols) > max(row_blacks)
        if vertical_side == 0:
            assert max(rows) < min(col_blacks)
        else:
            assert min(rows) > max(col_blacks)

    total_length = sum((2 + first_run + last_run) * len(cells)
                       for (_, _, first_run, last_run), cells in groups.items())
    assert total_length <= 6 * (2 * size - 2)


def verify_counterexample_inequalities():
    width = 256
    size = 1 << width
    # Lower bound: (2n-2)/(64e) > (2n-2)/192 >= n/128.
    assert Fraction(2 * size - 2, 192) >= Fraction(size, 128)
    # Layered upper bound: if k>n/256 then ln k > (L-8)/2 >= 256/e.
    # The rational check uses ln 2 > 1/2 and e > 5/2.
    assert Fraction(width - 8, 2) >= Fraction(512, 5)
    lower_exponent = (width - 7) * (2 * size - 2)
    upper_exponent = width + (width - 8) * 2 * size
    assert lower_exponent > upper_exponent




def word_masks(board):
    """Return one adjacency mask per nonempty across word."""
    size = len(board)
    black_row = [0] * size
    for row, col in enumerate(board):
        black_row[col] = row
    masks = []
    for row, black_col in enumerate(board):
        left = right = 0
        for col, split_row in enumerate(black_row):
            if col < black_col:
                left |= 1 << (2 * col + (row > split_row))
            if col > black_col:
                right |= 1 << (2 * col + (row > split_row))
        if left:
            masks.append(left)
        if right:
            masks.append(right)
    return tuple(sorted(masks, key=int.bit_count))


def rook_count(board):
    """Count perfect matchings by retaining the set of occupied down words."""
    masks = word_masks(board)

    @cache
    def count(used):
        row = used.bit_count()
        if row == len(masks):
            return 1
        available = masks[row] & ~used
        total = 0
        while available:
            choice = available & -available
            available -= choice
            total += count(used | choice)
        return total

    answer = count(0)
    count.cache_clear()
    return answer

def verify_small_published_counterexample():
    size = 17
    cuts = (0, 5, 8, 9, 12, 17)
    board = tuple(col for a, b in zip(cuts, cuts[1:])
                  for col in range(b - 1, a - 1, -1))
    assert rook_count(board) == 104_476_798_194_769
    stirling = [1]
    best = 0
    for m in range(1, size // 2 + 1):
        next_row = [0] * (m + 1)
        for k in range(1, m + 1):
            next_row[k] = stirling[k - 1]
            if k < len(stirling):
                next_row[k] += k * stirling[k]
        stirling = next_row
        value = sum((stirling[k] * factorial(k) * k ** (size - 2*m)) ** 2
                    for k in range(1, m + 1))
        best = max(best, value)
    assert best == 103_460_138_813_701


if __name__ == "__main__":
    for width in range(1, 13):
        verify_width(width)
    verify_counterexample_inequalities()
    verify_small_published_counterexample()
    print("Checked the groups through width 12, the width-256 inequality, and the published order-17 example.")

