#!/usr/bin/env python3
"""Exact arithmetic audit for the FPRD GapCVP parameter retuning.

This checks the seven concrete finite-N side conditions reported below for the
direct 3SAT-to-Euclidean-CVP reduction published by OpenAI at CVP exponent
c = 1/30. It does not reimplement the algebraic reduction and does not prove
the general retained-parameter frontier.
"""

from __future__ import annotations

from dataclasses import dataclass
from fractions import Fraction


@dataclass(frozen=True)
class Parameters:
    cvp_exponent: Fraction
    field_exponent: int
    support_exponent: int
    moment_exponent: int
    base: int = 100

    @property
    def binary_exponent(self) -> Fraction:
        return 2 * self.cvp_exponent

    @property
    def dimension_exponent(self) -> int:
        return 1 + 2 * self.field_exponent


def exact_discard_quarter_check(p: Parameters) -> bool:
    """Check the per-table exceptional-point loss is below one quarter."""

    a = p.binary_exponent.numerator
    b = p.binary_exponent.denominator
    margin_numerator = b * (p.support_exponent - 1) - a * p.dimension_exponent
    if margin_numerator <= 0:
        return False
    return 16**b * 40**a < p.base**margin_numerator


def audit(p: Parameters) -> dict[str, bool]:
    q = p.field_exponent
    k = p.support_exponent
    t = p.moment_exponent
    n = p.base

    return {
        "exceptional_points_below_q_over_4": exact_discard_quarter_check(p),
        "anchors_and_hankel_zeros_below_q_over_4": (
            4 * (n + n ** (1 + 2 * k)) < n**q
        ),
        "reconstruction_degree_below_q_over_2": (
            4 * n ** (1 + 2 * k + t) < n**q
        ),
        "reed_solomon_degree_below_q_over_2": 2 * n ** (1 + t) < n**q,
        "hankel_window": n**t >= 2 * n**k - 1,
        "parity_matching_window": n**t > 9 * n**k,
        "valuation_window": n**t > 5 * n ** (1 + 5 * k),
    }


def first_clean_parameters(
    cvp_denominator: int, max_field_exponent: int = 5000
) -> Parameters:
    """Find the first field exponent admitting the conservative certificate."""

    c = Fraction(1, cvp_denominator)
    for q in range(1, max_field_exponent + 1):
        for k in range(1, q + 1):
            t = 2 + 5 * k
            candidate = Parameters(c, q, k, t)
            if all(audit(candidate).values()):
                return candidate
    raise ValueError("no parameters found within search bound")


def main() -> None:
    chosen = Parameters(Fraction(1, 30), 242, 34, 172)
    results = audit(chosen)

    print("Chosen FPRD retuning")
    print(f"  CVP exponent c       = {chosen.cvp_exponent}")
    print(f"  binary exponent 2c   = {chosen.binary_exponent}")
    print(f"  q exponent Q         = {chosen.field_exponent}")
    print(f"  K exponent kappa     = {chosen.support_exponent}")
    print(f"  T exponent tau       = {chosen.moment_exponent}")
    print(f"  M exponent bound     = {chosen.dimension_exponent}")
    for name, passed in results.items():
        print(f"  {'PASS' if passed else 'FAIL'} {name}")
    if not all(results.values()):
        raise SystemExit(1)

    print("\nFirst conservative certificates")
    for denominator in (30, 29):
        candidate = first_clean_parameters(denominator)
        print(
            f"  c=1/{denominator}: "
            f"Q={candidate.field_exponent}, "
            f"kappa={candidate.support_exponent}, "
            f"tau={candidate.moment_exponent}, "
            f"M=O(N^{candidate.dimension_exponent})"
        )

    print("\nINFO retained frontier: proved separately from the three exponent inequalities")


if __name__ == "__main__":
    main()
