#!/usr/bin/env python3
"""Replay bounded Paper 1 examples using only exact arithmetic and the standard library.

Run: python3 replay-paper1-checks.py > paper1-checks.json
This program checks the equations on the stated inputs. It does not execute
Lean, implement the byte codecs, or simulate the commitment experiment.
"""

from collections import Counter, defaultdict
from fractions import Fraction
from itertools import product
import json

SOURCE = "eac922d4b54a6375f53bac0bb1522dec5c4dbd09"


def scalar_box() -> dict:
    fibers = defaultdict(Counter)
    for coupling, message, opening in product(range(-1, 2), repeat=3):
        point = (message - coupling * opening, coupling * message + opening)
        fibers[point][message] += 1
    wins = sum(max(counts.values()) for counts in fibers.values())
    assert (len(fibers), sum(len(counts) > 1 for counts in fibers.values()), wins) == (13, 6, 21)
    return {
        "states": 27,
        "distinct_observations": len(fibers),
        "ambiguous_observations": sum(len(counts) > 1 for counts in fibers.values()),
        "optimal_correct_guesses": wins,
        "fibers": [
            {"information_and_parity": view, "message_counts": dict(sorted(counts.items()))}
            for view, counts in sorted(fibers.items())
        ],
    }


def optimum(fibers: dict, total: int) -> str:
    """Choose the most frequent target separately in every observed bucket."""
    return str(Fraction(sum(max(bucket.values()) for bucket in fibers.values()), total))


def fresh_sign_disclosures() -> dict:
    sizes = []
    two_bit_buckets = {}
    for width in range(1, 5):
        signs = list(product((-1, 1), repeat=width))
        by_mask = defaultdict(Counter)
        by_prefix = [defaultdict(Counter) for _ in range(width + 1)]
        by_positive_count = defaultdict(Counter)
        by_singleton_test = defaultdict(Counter)
        for key, message in product(signs, repeat=2):
            mask = tuple(k * s for k, s in zip(key, message, strict=True))
            by_mask[mask][message] += 1
            for count, fibers in enumerate(by_prefix):
                fibers[(mask, key[:count])][message] += 1
            by_positive_count[(mask, key.count(1))][message] += 1
            by_singleton_test[(mask, key == (1,) * width)][message] += 1

        assert len(by_mask) == len(signs)
        assert all(
            len(counts) == len(signs) and set(counts.values()) == {1} for counts in by_mask.values()
        )
        total = len(signs) ** 2
        by_prefix_optimum = [optimum(fibers, total) for fibers in by_prefix]
        assert by_prefix_optimum == [
            str(Fraction(2**count, 2**width)) for count in range(width + 1)
        ]
        count_optimum = optimum(by_positive_count, total)
        assert count_optimum == str(Fraction(width + 1, 2**width))
        test_optimum = optimum(by_singleton_test, total)
        assert test_optimum == str(Fraction(2, 2**width))
        sizes.append(
            {
                "bits": width,
                "key_message_pairs": total,
                "distinct_masks": len(by_mask),
                "targets_per_mask": len(signs),
                "prefix_disclosure_optimum_by_number_of_signs": by_prefix_optimum,
                "positive_sign_count_optimum": count_optimum,
                "singleton_key_test_optimum": test_optimum,
            }
        )
        if width == 2:
            mask = (1, 1)
            two_bit_buckets = {
                "one_sign": sorted(
                    sum(counts.values())
                    for (view, _), counts in by_prefix[1].items()
                    if view == mask
                ),
                "singleton_key_test": sorted(
                    sum(counts.values())
                    for (view, _), counts in by_singleton_test.items()
                    if view == mask
                ),
                "population": len(signs),
            }
    assert two_bit_buckets == {"one_sign": [2, 2], "singleton_key_test": [1, 3], "population": 4}
    return {
        "sampling": "Uniform independent key and message signs. Condition on a mask.",
        "sizes": sizes,
        "two_bit_conditional_bucket_sizes": two_bit_buckets,
    }


def two_bit_lattice_costs() -> dict:
    # The manuscript takes A=((1,1),(1,-1)), a=3, key=(-1,1), message=(1,-1).
    point = (3, 0, 0, -6, 0)
    results = []
    for k1, k2 in product((-1, 1), repeat=2):
        expected = (-2 * k1, -2 * k2)  # The mask at this point is (-1, -1).
        costs = defaultdict(list)
        for z1, z2 in product(range(-3, 4), repeat=2):
            graph = (0, z1, z2, k1 * z1 + k2 * z2, k1 * z1 - k2 * z2)
            cost = sum((a - b) ** 2 for a, b in zip(point, graph, strict=True))
            costs[cost].append((z1, z2))
        first, second = sorted(costs)[:2]
        assert (first, second, costs[first]) == (21, 24, [expected])
        results.append(
            {"key": (k1, k2), "integer_coefficients": expected, "costs": [first, second]}
        )
    return {"point": point, "coefficient_box": [-3, 3], "candidates": results}


def key_relative_membership() -> dict:
    # Normal equations at the integer cochain (0, 0, 1) for two scalar matrices.
    results = []
    for b in (0, 1):
        coefficient = Fraction(b, 1 + b * b)
        accepted = coefficient.denominator == 1
        results.append(
            {"coupling": b, "projected_coefficient": str(coefficient), "accepted": accepted}
        )
    assert [result["accepted"] for result in results] == [True, False]
    return {"integer_cochain": [0, 0, 1], "results": results}


def scalar_transports() -> dict:
    coefficients = range(-2, 3)
    checked = 0
    for b, a, z, u in product(coefficients, repeat=4):
        source = (a, z - b * u, b * z + u)
        v = Fraction(source[1] + b * source[2], 1 + b * b)
        retained_opening = source[2] - b * v
        assert (v, retained_opening) == (z, u)
        for c in coefficients:
            target = (a, v - c * retained_opening, c * v + retained_opening)
            assert Fraction(target[1] + c * target[2], 1 + c * c) == z
            checked += 1
    assert checked == 3125
    return {"input_and_target_coupling_range": [-2, 2], "transports": checked}


def range_gate_checks() -> dict:
    bound, digits = 2, 3
    profiles = []
    for prime in (7, 17):
        admitted = []
        bounded_residues = {value % prime for value in range(-bound, bound + 1)}
        for plus, minus in product(range(2**digits), repeat=2):
            if (plus + minus - 2 * bound) % prime == 0:
                residue = (plus - bound) % prime
                if residue not in bounded_residues:
                    admitted.append({"residue": residue, "plus": plus, "minus": minus})
        profiles.append({"prime": prime, "accepted_pairs_without_bounded_lift": admitted})
    assert {"residue": 3, "plus": 5, "minus": 6} in profiles[0][
        "accepted_pairs_without_bounded_lift"
    ]
    assert profiles[1]["accepted_pairs_without_bounded_lift"] == []
    return {"bound": bound, "digits_per_side": digits, "profiles": profiles}


def parity_threshold() -> dict:
    checked = 0
    coefficients = list(product(range(-2, 3), repeat=3))
    for weights in product(range(4), repeat=3):
        subset_totals = {
            sum(weight * bit for weight, bit in zip(weights, bits, strict=True))
            for bits in product((0, 1), repeat=3)
        }
        for target in range(sum(weights) + 2):
            decision = any(
                (target - sum(w * z for w, z in zip(weights, point, strict=True))) ** 2
                + sum(z * z + (1 - z) ** 2 for z in point)
                <= 3
                for point in coefficients
            )
            assert decision == (target in subset_totals)
            checked += 1
    assert checked == 416
    return {
        "number_of_weights": 3,
        "weight_range": [0, 3],
        "coefficient_box": [-2, 2],
        "instances": checked,
    }


def main() -> None:
    checks = {
        "paper_revision": SOURCE,
        "scalar_box": scalar_box(),
        "fresh_sign_disclosures": fresh_sign_disclosures(),
        "two_bit_lattice_costs": two_bit_lattice_costs(),
        "key_relative_membership": key_relative_membership(),
        "scalar_transports": scalar_transports(),
        "range_gate": range_gate_checks(),
        "parity_threshold": parity_threshold(),
    }
    print(json.dumps(checks, indent=2))


if __name__ == "__main__":
    main()
