#!/usr/bin/env python3
"""Recompute the two illustrative Paper 2 figures by exact arithmetic.

This enumerates the small examples authored for the explainer. It does not run
the upstream owned-transfer fixture or check the general protocol theorems.
"""

from itertools import product
import json


def exact_artifact() -> dict:
    exact_opening = 1
    coupling = 1
    inputs = ((2, 1), (3, 1), (2, 0))
    ciphertexts = [
        (exact_opening, message - coupling * opening, coupling * message + opening)
        for message, opening in inputs
    ]
    assert ciphertexts == [(1, 1, 3), (1, 2, 4), (1, 2, 2)]
    assert all(x + y == 2 * message for (_, x, y), (message, _) in zip(ciphertexts, inputs))
    return {
        "coupling": coupling,
        "exact_component": (exact_opening, 0, 0),
        "inputs": [{"message": message, "coexact_opening": opening} for message, opening in inputs],
        "ciphertexts": ciphertexts,
    }


def scalar_fold() -> dict:
    prime = 5
    sites = tuple(range(1, prime))
    quadratic = tuple(x * x % prime for x in sites)
    lines = [tuple((a + b * x) % prime for x in sites) for a, b in product(range(prime), repeat=2)]
    folds = [tuple((1 + challenge) * value % prime for value in quadratic) for challenge in range(prime)]

    def distance(word, line):
        return sum(observed != predicted for observed, predicted in zip(word, line))

    nearest = [min(distance(fold, line) for line in lines) for fold in folds]
    paired_distances = [
        sum(a != observed or b != observed for (a, b), observed in zip(zip(first, second), quadratic))
        for first, second in product(lines, repeat=2)
    ]
    assert nearest == [2, 2, 2, 2, 0]
    assert min(paired_distances) == 2 and paired_distances.count(2) == 6
    return {
        "prime": prime,
        "sites": sites,
        "both_columns": quadratic,
        "allowed_polynomial_degree": 1,
        "strict_edit_cutoff": 2,
        "folds": folds,
        "fold_distances": nearest,
        "nearest_pair_count": paired_distances.count(2),
    }


if __name__ == "__main__":
    print(json.dumps({"exact_artifact": exact_artifact(), "scalar_fold": scalar_fold()}, indent=2))
