#!/usr/bin/env python3
"""Check the coordinate-encoded rank-five matroid with integer arithmetic."""

import json
import sys
from functools import cache
from itertools import product
from math import comb, isqrt, prod


def require(condition, message):
    if not condition:
        raise ValueError(message)


def remainder(poly, divisor, q):
    """Polynomial remainder modulo q, with a monic divisor."""
    coefficients = list(poly)
    degree = len(divisor) - 1
    for top in range(len(coefficients) - 1, degree - 1, -1):
        leading = coefficients[top]
        for index, coefficient in enumerate(divisor):
            position = top - degree + index
            coefficients[position] = (coefficients[position] - leading * coefficient) % q
    return tuple(coefficients[:degree])


def matrix_rank(rows, q):
    rows = [[entry % q for entry in row] for row in rows]
    if not rows:
        return 0
    rank = 0
    for column in range(len(rows[0])):
        pivot = next((i for i in range(rank, len(rows)) if rows[i][column]), None)
        if pivot is None:
            continue
        rows[rank], rows[pivot] = rows[pivot], rows[rank]
        inverse = pow(rows[rank][column], -1, q)
        for i in range(rank + 1, len(rows)):
            multiplier = rows[i][column] * inverse
            rows[i] = [(a - multiplier * b) % q for a, b in zip(rows[i], rows[rank])]
        rank += 1
    return rank


class Matroid:
    def __init__(self, data):
        require(isinstance(data, dict) and set(data) == {
            "prime", "field_modulus", "frobenius_indices", "auxiliary_index", "rank",
        }, "unexpected certificate fields")
        q = data["prime"]
        require(type(q) is int and q >= 2, "invalid field characteristic")
        require(all(q % d for d in range(2, isqrt(q) + 1)), "characteristic must be prime")
        modulus = data["field_modulus"]
        require(isinstance(modulus, list) and len(modulus) == 5 and
                all(type(c) is int and 0 <= c < q for c in modulus) and modulus[-1] == 1,
                "expected a monic quartic over the prime field")
        for degree in (1, 2):
            for low in product(range(q), repeat=degree):
                require(any(remainder(modulus, low + (1,), q)), "reducible field modulus")

        indices = data["frobenius_indices"]
        require(isinstance(indices, list) and all(type(i) is int for i in indices)
                and indices == list(range(4)), "invalid graph exponents")
        require(type(data["auxiliary_index"]) is int and data["auxiliary_index"] == 3,
                "the label must fix the last Frobenius coefficient")
        require(type(data["rank"]) is int and data["rank"] == 5, "expected rank five")
        self.q = q
        self.modulus = tuple(modulus)
        self.dim = len(modulus) - 1
        self.rank = data["rank"]
        self.exponents = tuple(q**i for i in indices)
        self.label_index = data["auxiliary_index"]
        self.labels = q**self.dim

        # Root bounds for interpolation on K and on a three-dimensional subspace.
        require(self.exponents[-1] < self.labels, "graph parameters are not certified unique")
        require(self.exponents[self.label_index - 1] < q**(self.dim - 1),
                "fixed-label interpolation is not certified unique")
        axes = [tuple(int(i == j) for j in range(2 * self.dim))
                for i in range(self.rank)]
        require(self.is_basis(axes), "could not establish the prescribed rank")

    def ground_set(self):
        """Iterate through normalized projective points and then auxiliary points."""
        coordinates = range(self.q)
        for lead in range(2 * self.dim):
            for tail in product(coordinates, repeat=2 * self.dim - lead - 1):
                yield (0,) * lead + (1,) + tail
        yield from product(coordinates, repeat=self.dim)

    def multiply(self, left, right):
        poly = [0] * (2 * self.dim - 1)
        for i, a in enumerate(left):
            for j, b in enumerate(right):
                poly[i + j] += a * b
        return remainder(poly, self.modulus, self.q)

    def power(self, value, exponent):
        result = (1,) + (0,) * (self.dim - 1)
        while exponent:
            if exponent & 1:
                result = self.multiply(result, value)
            exponent //= 2
            if exponent:
                value = self.multiply(value, value)
        return result

    def is_basis(self, points):
        """Decide membership in the coordinate-encoded family of bases."""
        if len(points) != self.rank or len(set(points)) != self.rank:
            return False
        geometric, auxiliary = [], []
        for point in points:
            if any(type(c) is not int or not 0 <= c < self.q for c in point):
                return False
            if len(point) == self.dim:
                auxiliary.append(point)
            elif len(point) == 2 * self.dim and next((c for c in point if c), 0) == 1:
                geometric.append(point)
            else:
                return False

        if matrix_rank(geometric, self.q) != len(geometric):
            return False
        if len(auxiliary) != 1:
            # A block has only four geometric dimensions and one auxiliary point.
            return True

        # Solve for the three free coefficients over F_q, in the power basis of K.
        units = [tuple(int(i == j) for j in range(self.dim)) for i in range(self.dim)]
        equations = []
        for point in geometric:
            t, y = point[:self.dim], point[self.dim:]
            powers = [self.power(t, exponent) for exponent in self.exponents]
            fixed = self.multiply(auxiliary[0], powers[self.label_index])
            columns = [self.multiply(unit, power)
                       for power in powers[:self.label_index] for unit in units]
            residual = tuple(a - b for a, b in zip(y, fixed))
            equations.extend(zip(*columns, residual))
        # A compatible system means the set is contained in a block.
        return matrix_rank(equations, self.q) > matrix_rank(
            [row[:-1] for row in equations], self.q
        )

    def flag_counts(self):
        q, d, m = self.q, self.dim, self.labels

        @cache
        def subspaces(n, k):
            # Divide the number of ordered independent k-tuples by the number
            # of ordered bases of a k-space.
            numerator = prod(q**n - q**i for i in range(k))
            denominator = prod(q**k - q**i for i in range(k))
            count, extra = divmod(numerator, denominator)
            require(extra == 0, "nonintegral subspace count")
            return count

        def nontransverse(k):
            # Choose the intersection with 0 x K, the first-coordinate image,
            # and the linear map from that image into K / intersection.
            return sum(subspaces(d, j) * subspaces(d, k - j) * q**((d - j) * (k - j))
                       for j in range(1, k + 1))

        # Old rank-four flats with zero or one auxiliary point survive exactly
        # when their geometric subspace has a nonzero vertical intersection.
        # All new hyperplanes are graphs with the label fixed by the graph.
        hyperplanes = [(d, 1, q**(d * len(self.exponents))),
                       (d, 0, nontransverse(d)),
                       (d - 1, 1, m * nontransverse(d - 1))]
        for t in range(2, d + 1):
            hyperplanes.append((d - t, t, subspaces(2 * d, d - t) * comb(m, t)))

        @cache
        def flags_below(n, t, ranks):
            if not ranks:
                return 1
            last = ranks[-1]
            return sum(subspaces(n, i) * comb(t, last - i) * flags_below(i, last - i, ranks[:-1])
                       for i in range(max(0, last - t), min(n, last) + 1))

        counts = {}
        for selected in product((False, True), repeat=d):
            ranks = tuple(i for i, include in enumerate(selected, 1) if include)
            if selected[-1]:
                counts[ranks] = sum(count * flags_below(n, t, ranks[:-1])
                                    for n, t, count in hyperplanes)
            else:
                counts[ranks] = flags_below(2 * d, m, ranks)
        return counts


def multiply_polynomials(left, right):
    result = [0] * (len(left) + len(right) - 1)
    for i, a in enumerate(left):
        for j, b in enumerate(right):
            result[i + j] += a * b
    return result


def chow_polynomials(rank, counts):
    """Expand CFH Proposition 4.6 by strict chains and apply Proposition 4.7."""
    chow = [0] * (rank + 1)
    augmented = [0] * (rank + 1)
    for ranks, count in counts.items():
        prefix = [count]
        previous = 0
        for current in ranks:
            gap = current - previous
            prefix = multiply_polynomials(prefix, [(-1)**(gap + 1)] * (gap + 1))
            previous = current
        gap = rank - previous
        # For F*, the last step is another inverse-kernel recursion step.
        # For H*, the last step carries (-x)^gap, or the identity if w = top.
        for i, value in enumerate(prefix):
            chow[i + gap] += (-1)**gap * value
            for j in range(gap + 1):
                augmented[i + j] += (-1)**(gap + 1) * value
    chow = [a + b for a, b in zip(chow, augmented)]  # w = top in Proposition 4.7
    require(chow[-1] == 0, "unexpected dual Chow degree")
    return chow[:-1], augmented


def gamma_and_discriminant(coefficients):
    degree = len(coefficients) - 1
    require(degree in (4, 5) and coefficients[-1] != 0, "unexpected polynomial degree")
    residual = coefficients[:]
    gamma = []
    for i in range(3):
        gamma.append(residual[i])
        for j in range(degree - 2 * i + 1):
            residual[i + j] -= gamma[i] * comb(degree - 2 * i, j)
    require(not any(residual), "gamma expansion did not reconstruct the polynomial")
    g0, g1, g2 = gamma
    discriminant = g1**2 - 4 * g0 * g2
    require(g0 > 0 and g2 > 0 and discriminant < 0, "no negative-discriminant witness")
    return gamma, discriminant


def main():
    try:
        require(len(sys.argv) == 2, "usage: python3 verify.py certificate.json")
        with open(sys.argv[1], encoding="utf-8") as source:
            matroid = Matroid(json.load(source))
        chow, augmented = chow_polynomials(matroid.rank, matroid.flag_counts())
        for name, polynomial in (("Dual Chow", chow), ("Dual right augmented Chow", augmented)):
            gamma, discriminant = gamma_and_discriminant(polynomial)
            print(f"{name} coefficients (constant first): {polynomial}")
            print(f"{name} gamma coefficients: {gamma}")
            print(f"{name} gamma discriminant: {discriminant}")
    except (ArithmeticError, OSError, ValueError, RecursionError) as error:
        print(f"Verification failed: {error}", file=sys.stderr)
        return 1
    print("VERIFIED")
    return 0


if __name__ == "__main__":
    sys.exit(main())
