"""Reconstruct the transfer matrix, and check its identities in Z[x,u]."""
from collections import Counter
from math import factorial

import sympy as sp


def transfer(u):
    matrix = sp.zeros(8)
    for occupied in range(8):
        matrix[occupied, occupied // 2] += u
        for offset in range(4):
            bit = 1 << offset
            if not occupied & bit:
                matrix[occupied, (occupied | bit) // 2] += 1
    return matrix


def count_board(n):
    """Enumerate placements row by row, tracking the actual n columns."""
    ways = Counter({0: 1})
    for row in range(n):
        updated = ways.copy()
        for used, count in ways.items():
            for col in {(row + offset) % n for offset in range(4)}:
                bit = 1 << col
                if not used & bit:
                    updated[used | bit] += count
        ways = updated
    by_deficit = Counter()
    for used, count in ways.items():
        by_deficit[n - bin(used).count("1")] += count
    return by_deficit


def main():
    x, u = sp.symbols("x u")
    mat = transfer(u)
    base = 1 - x - x**2 - x**3
    aux = x**5 + x**4 + 4*x**3 - x - 1
    den = (1 - x)**2 * base**2
    linear = -x*(x - 1)*aux
    determinant = den + linear*u + x**4*u**2
    assert sp.expand((sp.eye(8) - x*mat).det(method="domain-ge") - determinant) == 0
    assert sp.rem(aux, -base, x) == -2*x**2 - 4*x + 2

    raw = -x*sp.diff(linear/den, x)
    num = 33-69*x+16*x**2-14*x**3+82*x**4-8*x**5-20*x**6-38*x**7+9*x**8+9*x**9+8*x**10
    formula = x + 4*x**2 - 15*x**3 + x**3*num / ((1 - x)**2*base**3)
    assert sp.cancel(raw - 4*x**2 - 15*x**3 - formula) == 0

    # Enough distinct u values to identify each polynomial of degree <= n.
    board_counts = [count_board(n) for n in range(11)]
    for t in range(11):
        fixed = mat.subs(u, t)
        power = sp.eye(8)
        for n in range(1, 11):
            power = power * fixed
            if n >= 4:
                assert power.trace() == sum(c*t**d for d, c in board_counts[n].items())
    for n in range(1, 4):
        assert board_counts[n][1] == n**2 * factorial(n - 1)
    print("Verified determinant, cubic remainder, the published formula and all rook counts for 4 <= n <= 10.")


if __name__ == "__main__":
    main()
