"""Construct a complete placement on a permutation crossword grid."""

from collections import Counter
from itertools import permutations
from sys import argv


def nearest_lower(values, order):
    """Return the closest strictly smaller index in the scanned direction."""
    result = [None] * len(values)
    stack = []
    for index in order:
        while stack and values[stack[-1]] > values[index]:
            stack.pop()
        if stack:
            result[index] = stack[-1]
        stack.append(index)
    return result


def parents(values):
    """Find each min-Cartesian parent without building the tree recursively."""
    size = len(values)
    left = nearest_lower(values, range(size))
    right = nearest_lower(values, range(size - 1, -1, -1))
    for candidates in zip(left, right):
        yield max(
            (j for j in candidates if j is not None),
            key=values.__getitem__,
            default=None,
        )


def rook_placement(black_col):
    """Rows, columns and entries of black_col are numbered from zero."""
    black_row = [0] * len(black_col)
    for row, col in enumerate(black_col):
        black_row[col] = row
    rooks = set()
    for priorities in (black_row, [-row for row in black_row]):
        rooks.update(
            (black_row[parent], col)
            for col, parent in enumerate(parents(priorities))
            if parent is not None
        )
    return rooks


def verify(black_col, rooks):
    """Scan all white runs independently to check coverage and attacks."""
    size = len(black_col)
    counts = Counter()
    for col in range(size):
        for row in range(size):
            if black_col[row] == col:
                assert (row, col) not in rooks
                continue
            across = (row, col > black_col[row])
            counts["across", across] += (row, col) in rooks
    for col in range(size):
        above = True
        for row in range(size):
            if black_col[row] == col:
                above = False
                continue
            counts["down", (col, above)] += (row, col) in rooks
    assert all(value == 1 for value in counts.values()), (black_col, rooks)
    assert len(rooks) == 2 * size - 2


if __name__ == "__main__":
    limit = int(argv[1]) if len(argv) > 1 else 8
    checked = 0
    for size in range(1, limit + 1):
        for board in permutations(range(size)):
            verify(board, rook_placement(board))
            checked += 1
    print(f"Checked {checked:,} permutations of sizes 1 through {limit}.")

