"""Compare fplll LLL and BKZ on the existing 16-dimensional reference basis."""
import ast
from fractions import Fraction
import json
import math
from pathlib import Path
from statistics import median
import subprocess
from time import perf_counter_ns


def dot(left, right):
    return sum(x * y for x, y in zip(left, right))


def gram_schmidt_squared_norms(rows):
    orthogonal = []
    squared_norms = []
    for row in rows:
        residual = list(map(Fraction, row))
        for vector, squared_norm in zip(orthogonal, squared_norms):
            coefficient = dot(row, vector) / squared_norm
            residual = [x - coefficient * y for x, y in zip(residual, vector)]
        orthogonal.append(residual)
        squared_norms.append(dot(residual, residual))
    return squared_norms


def verify_lattice(reduced, original, expected_volume):
    # Solve for integer coefficients in the original upper-triangular row basis.
    for row in reduced:
        residual = row[:]
        for i, basis_row in enumerate(original):
            coefficient, remainder = divmod(residual[i], basis_row[i])
            assert remainder == 0
            residual = [x - coefficient * y for x, y in zip(residual, basis_row)]
        assert not any(residual)

    profile = gram_schmidt_squared_norms(reduced)
    assert math.prod(profile) == expected_volume**2
    return profile


def main():
    fixture = Path(__file__).with_name("g6k-lll-benchmark-results.json")
    reference = json.loads(fixture.read_text())
    basis = reference["basis_rows"]
    input_matrix = "[" + "\n".join(
        "[" + " ".join(map(str, row)) + "]" for row in basis
    ) + "]\n"
    results = []
    for name, options in [("LLL", ["-a", "lll"]), ("BKZ-8", ["-a", "bkz", "-b", "8"])]:
        timings = []
        for _ in range(34):
            start = perf_counter_ns()
            output = subprocess.run(
                ["fplll", *options, "-d", "0.99"],
                input=input_matrix, text=True, capture_output=True, check=True,
            ).stdout
            timings.append(perf_counter_ns() - start)
        matrix = output.replace("][", "]\n[").strip()[1:-1].strip()
        rows = [ast.literal_eval("[" + ",".join(line.strip()[1:-1].split()) + "]")
                for line in matrix.splitlines() if line.strip()]
        profile = verify_lattice(rows, basis, reference["covolume"])
        results.append({
            "algorithm": name,
            "median_ms": round(median(timings[3:]) / 1e6, 3),
            "first_vector_norm": round(math.sqrt(dot(rows[0], rows[0])), 4),
            "gs_norms": [round(math.sqrt(value), 4) for value in profile],
        })
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    main()
