"""Finite falsification check for the ordered-corner repair (Python 3.10+).

Run with: python check_construction.py
All 4-by-4 binary inputs, one reproducible greedy transversal per input,
pivot sizes 1 and 2, and both common residue offsets modulo 2 are checked.
The direct copy-count construction is also run on every nonfree matrix with
its theorem parameters and with a second fixed scale, at all block selections.
The general proof does not rely on this script or on transversal optimality.
"""

import sys
from functools import cache
from itertools import combinations, product


N = 4
L = 2
SINGLE = [1 << row for row in range(N)]
FULL = (1 << N) - 1
PAIRS = list(combinations(range(N), 2))


def pack(columns):
    return sum(bits << (N * col) for col, bits in enumerate(columns))


def unpack(matrix):
    return [(matrix >> (N * col)) & FULL for col in range(N)]


# Each mask describes four selected cells and the three that must be 1.
PATTERNS = []
for top, bottom in PAIRS:
    for left, right in PAIRS:
        first = (SINGLE[top] | SINGLE[bottom]) << (N * left)
        ones = first | (SINGLE[bottom] << (N * right))
        PATTERNS.append((ones | (SINGLE[top] << (N * right)), ones))


@cache
def copies(matrix):
    return tuple(mask for mask, ones in PATTERNS if matrix & mask == ones)


def greedy_transversal(matrix):
    remaining = copies(matrix)
    marks = 0
    while remaining:
        cells = (1 << index for index in range(N * N))
        chosen = max(cells, key=lambda cell: sum(bool(cell & w) for w in remaining))
        marks |= chosen
        remaining = [w for w in remaining if not w & chosen]
    return marks


def pivot(columns, marks, size):
    groups = []
    unused = list(range(N))
    draft = [0] * N
    rounded = [0] * N
    for row in reversed(range(N)):
        bit = SINGLE[row]
        group = [c for c in unused if columns[c] & bit and not marks[c] & bit]
        if len(group) < size:
            continue
        groups.append(group)
        unused = [c for c in unused if c not in group]
        for upper in range(row + 1):
            top = SINGLE[upper]
            known = [not marks[c] & top for c in group]
            entries = [bool(columns[c] & top) for c in group]
            # The largest minimizing cut starts at the first forced one if possible.
            def mismatches(cut):
                return sum(fixed and (bit != (j >= cut))
                           for j, (bit, fixed) in enumerate(zip(entries, known)))
            cut = min(reversed(range(len(group) + 1)), key=mismatches)
            for j, c in enumerate(group):
                if j >= cut:
                    draft[c] |= top
                if (j >= cut) != entries[j]:
                    rounded[c] |= top
    return draft, groups, rounded


@cache
def closure(ancestors, support):
    result = 0
    for row, bit in enumerate(SINGLE):
        if support & bit:
            result |= ancestors[row]
    return result


@cache
def append_column(ancestors, support):
    result = list(ancestors)
    for row, bit in enumerate(SINGLE):
        seeds = ancestors[row]
        if support & bit:
            seeds |= support & (bit - 1)
        for upper in range(row):
            if seeds & SINGLE[upper]:
                result[row] |= result[upper]
    return tuple(result)


def interpolate(draft, groups, sample, bad_rows, gap):
    owner = {c: k for k, group in enumerate(groups) for c in group}
    cleaned = [support & ~bad_rows for support in draft]
    restricted = pack([bits if c in sample else 0 for c, bits in enumerate(cleaned)])
    assert not copies(restricted)

    latest = [0] * len(groups)
    ancestors = tuple(SINGLE)
    output = []
    enlarged = 0
    for c in range(N):
        if c in sample:
            support = cleaned[c]
            assert closure(ancestors, support) == support
            ancestors = append_column(ancestors, support)
            latest[owner[c]] = support
        else:
            previous = latest[owner[c]] if c in owner else 0
            support = closure(ancestors, previous)
            enlarged += support != previous
            assert append_column(ancestors, support) == ancestors
        assert not support & bad_rows
        output.append(support)
    for group in groups:
        assert all(output[a] & ~output[b] == 0 for a, b in zip(group, group[1:]))
        for row_bit in SINGLE:
            errors = sum(bool((output[c] ^ cleaned[c]) & row_bit) for c in group)
            assert errors <= gap
    result = pack(output)
    assert not copies(result)
    return result, enlarged


@cache
def inversion_cover(first, second):
    """Delete a minimum set meeting every earlier-first / later-second pair."""
    cuts = [(1 << j) - 1 for j in range(N + 1)]
    return min(((first & left) | (second & ~left) for left in cuts),
               key=int.bit_count)


def direct_check(matrix, size, block_len, threshold):
    columns = unpack(matrix)
    rows = [sum(SINGLE[c] for c in range(N) if columns[c] & bit) for bit in SINGLE]
    scores = [0] * N
    for top, bottom in PAIRS:
        first = rows[top] & rows[bottom]
        second = ~rows[top] & rows[bottom]
        scores[bottom] += inversion_cover(first, second).bit_count()
    col_covers = {(a, b): inversion_cover(columns[a] & ~columns[b], columns[a] & columns[b])
                  for a, b in PAIRS}
    cover_sum = sum(x.bit_count() for x in col_covers.values())
    number = len(copies(matrix))
    assert max(sum(scores), cover_sum) ** 2 <= 4 * N ** 2 * number

    heavy = sum(SINGLE[r] for r, score in enumerate(scores) if score > threshold)
    live = [support & ~heavy for support in columns]
    draft, groups, rounded = pivot(live, [0] * N, size)
    rough, edits = pack(draft), pack(rounded)
    assert edits.bit_count() <= len(groups) * threshold
    assert (rough ^ pack(live)).bit_count() <= N * (size - 1) + edits.bit_count()
    assert all(w & edits or w in copies(matrix) for w in copies(rough))

    blocks = [group[start:start + block_len] for group in groups
              for start in range(0, len(group) - block_len + 1, block_len)]
    count = bad_sum = pair_deletions = 0
    for selection in product(*blocks):
        sample = set(selection)
        bad = 0
        for c in sample:
            bad |= rounded[c]
        for pair in combinations(sorted(sample), 2):
            pair_deletions += bool(col_covers[pair] & ~(bad | heavy))
            bad |= col_covers[pair]
        result, _ = interpolate(draft, groups, sample, bad, 2 * (block_len - 1))
        rows_zeroed = (bad | heavy).bit_count()
        bound = (N * (rows_zeroed + size - 1 + 2 * len(groups) * (block_len - 1))
                 + edits.bit_count())
        assert (result ^ matrix).bit_count() <= bound
        count += 1
        bad_sum += bad.bit_count()
    assert bad_sum * block_len ** 2 <= count * (edits.bit_count() * block_len + cover_sum)
    return count, pair_deletions


def theorem_parameters(number):
    # For lambda=(number/N^4)^(1/10), compute both ceilings and the floor exactly.
    size = next(s for s in range(1, N + 1) if s**10 >= N**6 * number)
    length = next(k for k in range(1, N + 1) if k**5 >= N * number)
    threshold = max(h for h in range(N**2 + 1) if h**5 <= N**2 * number**2)
    return size, length, threshold


def main():
    if not __debug__:
        raise RuntimeError("Run without the -O flag so the checks are active.")
    inputs = 1 << (N * N)
    runs = enlarged = nonfree = direct_runs = pair_deletions = 0
    for matrix in range(inputs):
        hit = greedy_transversal(matrix)
        nonfree += bool(hit)
        marks = unpack(hit)
        cells = hit.bit_count()
        for size in (1, 2):
            draft, groups, rounded = pivot(unpack(matrix), marks, size)
            assert not pack(rounded) & ~hit
            rough = pack(draft)
            assert all(w & hit for w in copies(rough))
            assert (rough ^ matrix).bit_count() <= N * (size - 1) + cells
            bad_count_sum = 0
            for offset in range(L):
                sample = {c for group in groups for c in group[offset::L]}
                bad = 0
                for c in sample:
                    bad |= marks[c]
                output, growth = interpolate(draft, groups, sample, bad, L - 1)
                bad_count = bad.bit_count()
                bound = N * (size - 1) + cells + N * (bad_count + len(groups) * (L - 1))
                assert (output ^ matrix).bit_count() <= bound
                bad_count_sum += bad_count
                runs += 1
                enlarged += growth
            assert bad_count_sum <= cells
        if hit:
            for parameters in (theorem_parameters(len(copies(matrix))), (1, 2, 4)):
                count, deletions = direct_check(matrix, *parameters)
                direct_runs += count
                pair_deletions += deletions
    print(f"Python {sys.version.split()[0]}; {inputs} matrices ({nonfree} with copies)")
    print(f"{runs} full repairs; {enlarged} inserted supports strictly above their anchors")
    print(f"{direct_runs} direct-construction repairs; {pair_deletions} sampled pairs added live rows to the deletion set")
    print("All checks passed.")


if __name__ == "__main__":
    main()
