#!/usr/bin/env python3
"""Reproduce the article's card-packet illustrations. No secret board is printed."""
import json
import runpy
from collections import Counter
from itertools import permutations, product
from pathlib import Path
from random import Random


DIRECTORY = Path(__file__).resolve().parent
CLUES = ("0..1", "10..", "..0.", "1...")


def columns(board):
    return ["".join(column) for column in zip(*board)]


def meets_clues(board):
    return all(clue == "." or clue == bit
               for row, clue_row in zip(board, CLUES)
               for bit, clue in zip(row, clue_row))


def satisfies_rules(board):
    for lines in (board, columns(board)):
        if len(set(lines)) != len(lines):
            return False
        if any(line.count("1") != len(line) // 2 or "000" in line or "111" in line
               for line in lines):
            return False
    return True


def balance_round(board, direction, seed):
    # The seed is public and fixed solely to reproduce the example transcript.
    # It models the card moves, not a private or trustworthy shuffle service.
    rng = Random(seed)
    size = len(board)
    rows = rng.sample(range(size), size)
    cols = rng.sample(range(size), size)
    second_grid = ["".join(board[r][c] for c in cols) for r in rows]
    packets = second_grid if direction == "rows" else columns(second_grid)
    opened = ["".join(rng.sample(cards, size)) for cards in packets]
    failed = [i for i, cards in enumerate(opened, 1) if cards.count("1") != size // 2]
    return {"opened_packets": opened, "failed_packets": failed, "accepted": not failed}


def shuffle_counts(cards):
    # Distinct positions are the four physical cards, including equal-faced pairs.
    return Counter("".join(cards[i] for i in order)
                   for order in permutations(range(len(cards))))


def triple_offsets(line, offsets):
    # A skip of e makes position e+1 the first card using the paper's 1-based labels.
    starts = sorted(start for e in offsets for start in range(e, len(line) - 2, 3))
    return {
        "starts_1_based": [i + 1 for i in starts],
        "uniform_triples_detected_at": [i + 1 for i in starts if len(set(line[i:i+3])) == 1],
    }


def main():
    size = len(CLUES)
    balanced_lines = ["".join(bits) for bits in product("01", repeat=size)
                      if bits.count("1") == size // 2]
    boards = [board for board in product(balanced_lines, repeat=size) if satisfies_rules(board)]
    matches = [board for board in boards if meets_clues(board)]
    assert len(boards) == 72 and len(matches) == 1
    witness = matches[0]
    solver = runpy.run_path(str(DIRECTORY / "binary-puzzle-solver.py"))
    cells, n = solver["parse"]("\n".join(CLUES))
    solver_count, solution, _ = solver["count_solutions"](cells, n)
    assert solver_count == 1 and "".join(map(str, solution)) == "".join(witness)

    valid_rows = balance_round(witness, "rows", 24)
    valid_columns = balance_round(witness, "columns", 51)
    assert valid_rows["accepted"] and valid_columns["accepted"]
    assert valid_rows["opened_packets"] == ["1001", "1010", "0110", "0011"]

    # Flip the unpublished value in the second cell of the first row.
    assert CLUES[0][1] == "."
    damaged = list(witness)
    damaged[0] = damaged[0][:1] + str(1 - int(damaged[0][1])) + damaged[0][2:]
    damaged_rows = balance_round(damaged, "rows", 24)
    damaged_columns = balance_round(damaged, "columns", 51)
    assert meets_clues(damaged) and not satisfies_rules(damaged)
    assert damaged_rows["failed_packets"] == [3] and damaged_rows["opened_packets"][2] == "0111"
    assert len(damaged_columns["failed_packets"]) == 1

    alternating = ["".join(str((r + c) % 2) for c in range(size)) for r in range(size)]
    alternating_rows = balance_round(alternating, "rows", 24)
    alternating_columns = balance_round(alternating, "columns", 51)
    assert meets_clues(alternating) and not satisfies_rules(alternating)
    assert alternating_rows["accepted"] and alternating_columns["accepted"]

    simulated = shuffle_counts("0011")  # A simulator can start with these four public card faces.
    assert len(simulated) == 6 and set(simulated.values()) == {4}
    assert all(shuffle_counts(line) == simulated for line in balanced_lines)
    edges = {}
    for line in ("000101", "00011011"):
        printed = triple_offsets(line, (1, 2, 3))
        all_offsets = triple_offsets(line, (0, 1, 2))
        assert printed["uniform_triples_detected_at"] == []
        assert all_offsets["uniform_triples_detected_at"] == [1]
        edges[line] = {"printed_offsets_1_2_3": printed, "offsets_0_1_2": all_offsets}

    result = {
        "scope": "Deterministic illustration of the balance branch in section 3.1, plus a separate check of its printed triple indices. No full protocol or security implementation.",
        "source": "https://doi.org/10.4230/LIPIcs.FUN.2016.8",
        "public_clues": CLUES,
        "valid_4x4_completions_before_clues": len(boards),
        "completions_matching_all_six_clues": len(matches),
        "site_solver_solution_count": solver_count,
        "correct_board": {"row_round": valid_rows, "separate_column_round": valid_columns},
        "one_flipped_nongiven": {"row_round": damaged_rows, "separate_column_round": damaged_columns},
        "alternating_control": {
            "public_clues_match": meets_clues(alternating),
            "distinct_row_count": len(set(alternating)),
            "distinct_column_count": len(set(columns(alternating))),
            "row_balance_accepted": alternating_rows["accepted"],
            "column_balance_accepted": alternating_columns["accepted"],
        },
        "single_packet_enumeration": {
            "balanced_initial_face_strings_tested": len(balanced_lines),
            "physical_orders_per_initial_string": sum(simulated.values()),
            "face_string_counts_for_every_balanced_start": dict(sorted(simulated.items())),
        },
        "adjacency_index_examples": edges,
    }
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
