#!/usr/bin/env python3
"""
ONE BIG BACKEND — SHIELD 1: FINE-GRAINED `#OV` PROOF-OF-WORK (v2 HARDENED)
(`obb_fine_grained_pow.py`)
License: GNU AGPLv3
External Dependencies: 0 (100% Python Standard Library + local `obb_primitives` & `obb_epistemic_lattice`)

Literature Lineage:
  - Ball, Rosen, Sabin, Vasudevan, "Average-Case Fine-Grained Hardness" (STOC 2017)
  - Ball, Rosen, Sabin, Vasudevan, "Proofs of Work from Worst-Case Assumptions" (CRYPTO 2018)

Evaluates the counting Orthogonal Vectors polynomial over the 127-bit Mersenne prime field
F_p (p = 2^127 - 1):

    pOV(U, V) = Sum_{i=1..n} Sum_{j=1..n} Prod_{l=1..d} (1 - U_{i,l} * V_{j,l})  mod p

v2 Security & Complexity Fixes (vs. v1):
  1. MONOMIAL-FACTORIZATION GUARD: At small constant d (e.g., d=3 or d=4), expanding the
     inner product yields an exact O(2^d * n) linear-time cheat:
         pOV(U, V) = Sum_{S subset [d]} (-1)^|S| (Sum_i Prod_{l in S} U_{i,l}) (Sum_j Prod_{l in S} V_{j,l})
     Production issuers therefore enforce `d >= max(16, 2 * ceil(log2(n)))` so 2^d >= n^2
     (with explicit `allow_toy_params=True` required for small fast unit-test/UI parameters).
  2. UNAUTHENTICATED EPOCH-ROTATION DoS FIX: `issue_challenge()` NEVER triggers O(d * n^2)
     epoch rotation on raw unauthenticated requests. Rotation occurs only via explicit
     operator/scheduler `rotate_epoch()` or after `epoch_max_verified` *verified* solves,
     and `_pending` enforces strict TTL expiration + bounded max capacity.
  3. HONEST `P = NP` / SETH COMPLEXITY SCOPE: `P = NP` refutes SETH. Shield 1 survives
     `P = NP` ONLY CONDITIONALLY on the weaker in-P fine-grained #OV lower bound
     (Omega(n^{2-o(1)})), providing a polynomial anti-Sybil speed bump rather than
     exponential cryptographic secrecy.
"""

from __future__ import annotations

import json
import math
import secrets
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple

from obb_epistemic_lattice import (
    EpistemicClaim,
    EpistemicTruth,
    SourceKind,
    SweetbrierEpistemicGate,
)
from obb_primitives import ObbSafetyFloor

MERSENNE_P: int = (1 << 127) - 1
Matrix = Tuple[Tuple[int, ...], ...]


class FineGrainedPowError(PermissionError):
    """Raised when a Fine-Grained #OV Proof-of-Work solution fails verification, replays, or expires."""


def min_secure_dimension(n: int) -> int:
    """
    Minimum dimension d defeating the exact O(2^d * n) monomial-factorization attack
    (requires 2^d >= n^2 and d >= 16 to stay clear of small-constant polynomial-method regimes).
    """
    if n < 4:
        raise ValueError("n must be >= 4.")
    return max(16, 2 * math.ceil(math.log2(n)))


def _rand_field() -> int:
    return secrets.randbelow(MERSENNE_P)


def _rand_nonzero_field() -> int:
    return 1 + secrets.randbelow(MERSENNE_P - 1)


def _rand_matrix(n: int, d: int) -> Matrix:
    return tuple(tuple(_rand_field() for _ in range(d)) for _ in range(n))


def _random_perm(size: int) -> List[int]:
    arr = list(range(size))
    for i in range(size - 1, 0, -1):
        j = secrets.randbelow(i + 1)
        arr[i], arr[j] = arr[j], arr[i]
    return arr


def evaluate_pov(u_mat: Sequence[Sequence[int]], v_mat: Sequence[Sequence[int]]) -> int:
    """
    Direct evaluation of the Orthogonal-Vectors polynomial over F_(2^127 - 1):
        pOV(U, V) = Sum_{i=0..n-1} Sum_{j=0..n-1} Prod_{l=0..d-1} (1 - U[i][l] * V[j][l]) mod p
    Runs in Theta(d * n^2) arithmetic operations.
    """
    p = MERSENNE_P
    total = 0
    for u_row in u_mat:
        d = len(u_row)
        for v_row in v_mat:
            prod = 1
            for col in range(d):
                term = (1 - u_row[col] * v_row[col]) % p
                prod = (prod * term) % p
            total = (total + prod) % p
    return total


def evaluate_pov_monomial_attack(
    u_mat: Sequence[Sequence[int]],
    v_mat: Sequence[Sequence[int]],
) -> int:
    """
    Red-team reference implementation of the exact O(2^d * n) linear-time monomial attack:
        pOV(U, V) = Sum_{S subset [d]} (-1)^|S| (Sum_i Prod_{l in S} U[i][l]) (Sum_j Prod_{l in S} V[j][l]) mod p

    Demonstrates why small constant d (e.g. d=3 or d=4) completely breaks quadratic hardness,
    and why `FineGrainedOvIssuer` enforces `d >= min_secure_dimension(n)` in production.
    Refuses d > 20 in this helper purely to avoid accidental RAM/CPU hang in local tests.
    """
    p = MERSENNE_P
    d = len(u_mat[0])
    if d > 20:
        raise ValueError(f"Monomial attack infeasible/blocked at d={d} (2^{d} = {1 << d} subsets).")

    n = len(u_mat)
    # Build subset products incrementally via DP over bitmasks: O(2^d * n) field muls
    u_dp = [[1] * (1 << d) for _ in range(n)]
    v_dp = [[1] * (1 << d) for _ in range(n)]
    for mask in range(1, 1 << d):
        lsb = mask & -mask
        bit = lsb.bit_length() - 1
        prev = mask ^ lsb
        for i in range(n):
            u_dp[i][mask] = (u_dp[i][prev] * u_mat[i][bit]) % p
            v_dp[i][mask] = (v_dp[i][prev] * v_mat[i][bit]) % p

    total = 0
    for mask in range(1 << d):
        sum_u = 0
        sum_v = 0
        for i in range(n):
            sum_u += u_dp[i][mask]
            sum_v += v_dp[i][mask]
        term = ((sum_u % p) * (sum_v % p)) % p
        if mask.bit_count() & 1:
            total = (total - term) % p
        else:
            total = (total + term) % p
    return total


def apply_pov_automorphism(
    u_mat: Matrix,
    v_mat: Matrix,
) -> Tuple[Matrix, Matrix]:
    """
    Apply a fresh pOV-preserving automorphism:
      - independent row permutations pi_U, pi_V in S_n
      - shared column permutation pi_c in S_d
      - reciprocal diagonal column scaling alpha_l in F_p* on U and alpha_l^-1 on V
    Preserves pOV(U_tilde, V_tilde) == pOV(U, V) mod p identically.
    """
    p = MERSENNE_P
    n = len(u_mat)
    d = len(u_mat[0])
    pi_u = _random_perm(n)
    pi_v = _random_perm(n)
    pi_c = _random_perm(d)
    alphas = [_rand_nonzero_field() for _ in range(d)]
    inv_alphas = [pow(a, -1, p) for a in alphas]

    u_tilde = tuple(
        tuple((u_mat[pi_u[i]][pi_c[col]] * alphas[col]) % p for col in range(d))
        for i in range(n)
    )
    v_tilde = tuple(
        tuple((v_mat[pi_v[j]][pi_c[col]] * inv_alphas[col]) % p for col in range(d))
        for j in range(n)
    )
    return u_tilde, v_tilde


def lagrange_eval_at(points: Sequence[Tuple[int, int]], x_target: int) -> int:
    """Exact Lagrange interpolation over F_(2^127 - 1) evaluating the unique degree-(k-1) curve at x_target."""
    p = MERSENNE_P
    k = len(points)
    acc = 0
    for i in range(k):
        xi, yi = points[i]
        num = 1
        den = 1
        for j in range(k):
            if i == j:
                continue
            xj = points[j][0]
            num = (num * ((x_target - xj) % p)) % p
            den = (den * ((xi - xj) % p)) % p
        acc = (acc + yi * num * pow(den, -1, p)) % p
    return acc


@dataclass(frozen=True)
class FineGrainedChallenge:
    """Public #OV polynomial curve challenge issued to a client."""

    challenge_id: str
    n: int
    d: int
    num_eval_points: int
    u0: Matrix
    r_u: Matrix
    v0: Matrix
    r_v: Matrix
    soundness_error_bound: float
    toy_parameters: bool = False


@dataclass(frozen=True)
class FineGrainedSolution:
    """Compact solution returned by the client: 2*d + 1 field integers."""

    challenge_id: str
    evaluations: Tuple[int, ...]


def solve_ov_challenge(challenge: FineGrainedChallenge) -> FineGrainedSolution:
    """
    Client solver: evaluates y_k = pOV(U0 + k * R_U, V0 + k * R_V) for k = 1 .. 2*d + 1.
    Requires Theta(d^2 * n^2) work when d >= min_secure_dimension(n).
    """
    p = MERSENNE_P
    n = challenge.n
    d = challenge.d
    evals: List[int] = []
    for k in range(1, challenge.num_eval_points + 1):
        u_k = [
            [(challenge.u0[i][col] + k * challenge.r_u[i][col]) % p for col in range(d)]
            for i in range(n)
        ]
        v_k = [
            [(challenge.v0[j][col] + k * challenge.r_v[j][col]) % p for col in range(d)]
            for j in range(n)
        ]
        evals.append(evaluate_pov(u_k, v_k))
    return FineGrainedSolution(challenge_id=challenge.challenge_id, evaluations=tuple(evals))


class FineGrainedOvIssuer:
    """
    Hardened issuer and O(d^2) microsecond verifier for Ball-Rosen-Sabin-Vasudevan
    #OV Fine-Grained Proof-of-Work (STOC 2017 / CRYPTO 2018).
    """

    def __init__(
        self,
        n: int = 256,
        d: int = 16,
        epoch_max_verified: int = 64,
        max_pending: int = 1024,
        challenge_ttl_seconds: float = 120.0,
        allow_toy_params: bool = False,
    ) -> None:
        if n < 4 or d < 2:
            raise ValueError("FineGrainedOvIssuer requires n >= 4 and d >= 2.")
        req_d = min_secure_dimension(n)
        if d < req_d and not allow_toy_params:
            raise ValueError(
                f"Insecure #OV dimension d={d} for n={n}: vulnerable to O(2^d * n) monomial "
                f"factorization attack. Require d >= {req_d} (or pass allow_toy_params=True "
                f"explicitly for non-production tests)."
            )
        if epoch_max_verified < 1 or max_pending < 1 or challenge_ttl_seconds <= 0:
            raise ValueError("Invalid issuer operational bounds.")

        self.n = n
        self.d = d
        self.allow_toy_params = allow_toy_params
        self.epoch_max_verified = epoch_max_verified
        self.max_pending = max_pending
        self.challenge_ttl_seconds = challenge_ttl_seconds

        self._epoch_id = 0
        self._epoch_verified_solves = 0
        self._u_star: Matrix = ()
        self._v_star: Matrix = ()
        self._y_star: int = 0
        # Bounded FIFO/TTL map: challenge_id -> (r_star, expected_y_star, expires_at_mono)
        self._pending: "OrderedDict[str, Tuple[int, int, float]]" = OrderedDict()
        self._burned_ids: "OrderedDict[str, float]" = OrderedDict()
        self.rotate_epoch()

    @property
    def epoch_id(self) -> int:
        return self._epoch_id

    @property
    def pending_count(self) -> int:
        return len(self._pending)

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

    @property
    def soundness_error_bound(self) -> float:
        return (2 * self.d) / float(MERSENNE_P - self.num_eval_points)

    def _evict_expired(self, now: float) -> None:
        while self._pending:
            cid, (_, _, exp) = next(iter(self._pending.items()))
            if exp <= now or len(self._pending) > self.max_pending:
                self._pending.popitem(last=False)
            else:
                break
        while self._burned_ids:
            cid, exp = next(iter(self._burned_ids.items()))
            if exp <= now or len(self._burned_ids) > self.max_pending * 4:
                self._burned_ids.popitem(last=False)
            else:
                break

    def rotate_epoch(self) -> None:
        """
        Rotate base epoch instance (U*, V*, y*).
        Called ONLY during initialization, scheduled background maintenance, or after
        `epoch_max_verified` legitimately verified solves — NEVER on unauthenticated issuance.
        """
        self._epoch_id += 1
        self._epoch_verified_solves = 0
        self._u_star = _rand_matrix(self.n, self.d)
        self._v_star = _rand_matrix(self.n, self.d)
        self._y_star = evaluate_pov(self._u_star, self._v_star)

    def issue_challenge(self) -> FineGrainedChallenge:
        """
        Issue a fresh automorphism-randomized, double-blinded #OV curve challenge in O(n*d).
        Zero quadratic server work on unauthenticated requests.
        """
        now = time.monotonic()
        self._evict_expired(now)
        if len(self._pending) >= self.max_pending:
            self._pending.popitem(last=False)

        p = MERSENNE_P
        u_tilde, v_tilde = apply_pov_automorphism(self._u_star, self._v_star)
        r_u = _rand_matrix(self.n, self.d)
        r_v = _rand_matrix(self.n, self.d)

        min_r = self.num_eval_points + 1
        r_star = min_r + secrets.randbelow(p - min_r)

        u0 = tuple(
            tuple((u_tilde[i][col] - r_star * r_u[i][col]) % p for col in range(self.d))
            for i in range(self.n)
        )
        v0 = tuple(
            tuple((v_tilde[j][col] - r_star * r_v[j][col]) % p for col in range(self.d))
            for j in range(self.n)
        )

        chal_id = f"FGOV-E{self._epoch_id:03d}-{secrets.token_hex(8).upper()}"
        self._pending[chal_id] = (r_star, self._y_star, now + self.challenge_ttl_seconds)
        return FineGrainedChallenge(
            challenge_id=chal_id,
            n=self.n,
            d=self.d,
            num_eval_points=self.num_eval_points,
            u0=u0,
            r_u=r_u,
            v0=v0,
            r_v=r_v,
            soundness_error_bound=self.soundness_error_bound,
            toy_parameters=self.d < min_secure_dimension(self.n),
        )

    def verify_solution(self, solution: FineGrainedSolution) -> bool:
        """
        Verify a client solution in O(d^2) microseconds via Lagrange interpolation at secret r*.
        Burns challenge_id on first verification attempt (replay-proof).
        """
        now = time.monotonic()
        self._evict_expired(now)

        cid = solution.challenge_id
        if cid in self._burned_ids:
            raise FineGrainedPowError(f"Replay detected: challenge '{cid}' was already consumed.")
        if cid not in self._pending:
            raise FineGrainedPowError(f"Unknown or expired challenge '{cid}'.")

        r_star, expected_y, exp = self._pending.pop(cid)
        self._burned_ids[cid] = exp
        if exp <= now:
            raise FineGrainedPowError(f"Challenge '{cid}' expired before verification.")

        if len(solution.evaluations) != self.num_eval_points:
            raise FineGrainedPowError(
                f"Malformed solution: expected {self.num_eval_points} evaluations, got {len(solution.evaluations)}."
            )
        for val in solution.evaluations:
            if not (0 <= val < MERSENNE_P):
                raise FineGrainedPowError("Solution evaluation outside F_(2^127 - 1).")

        points = [(k + 1, solution.evaluations[k]) for k in range(self.num_eval_points)]
        interpolated = lagrange_eval_at(points, r_star)
        if interpolated != expected_y:
            raise FineGrainedPowError(
                "Fine-Grained #OV verification FAILED: forged or incorrect polynomial evaluations."
            )

        self._epoch_verified_solves += 1
        if self._epoch_verified_solves >= self.epoch_max_verified:
            self.rotate_epoch()
        return True


class ObbSanctuaryPowGate:
    """Zero-CAPTCHA, Zero-PII public civic admission gate combining Shield 1 + Layer 0."""

    def __init__(
        self,
        node_id: str,
        n: int = 256,
        d: int = 16,
        allow_toy_params: bool = False,
    ) -> None:
        self.issuer = FineGrainedOvIssuer(n=n, d=d, allow_toy_params=allow_toy_params)
        self.safety_floor = ObbSafetyFloor()
        self.epistemic_gate = SweetbrierEpistemicGate(node_id=node_id, safety_floor=self.safety_floor)

    def admit_public_submission(
        self,
        solution: FineGrainedSolution,
        claim_id: str,
        subject: str,
        payload: Mapping[str, Any],
        source_kind: SourceKind,
        source_id: str,
        proposed_truth: EpistemicTruth = EpistemicTruth.UNKNOWN,
    ) -> EpistemicClaim:
        self.issuer.verify_solution(solution)
        return self.epistemic_gate.ingest(
            claim_id=claim_id,
            subject=subject,
            payload=payload,
            proposed_truth=proposed_truth,
            source_kind=source_kind,
            source_id=source_id,
            note=f"Admitted via Fine-Grained #OV PoW ({solution.challenge_id}).",
        )


if __name__ == "__main__":
    issuer = FineGrainedOvIssuer(n=256, d=16)
    t0 = time.perf_counter()
    chal = issuer.issue_challenge()
    t_issue_ms = (time.perf_counter() - t0) * 1000.0
    t1 = time.perf_counter()
    sol = solve_ov_challenge(chal)
    t_solve_ms = (time.perf_counter() - t1) * 1000.0
    t2 = time.perf_counter()
    ok = issuer.verify_solution(sol)
    t_verify_ms = (time.perf_counter() - t2) * 1000.0
    print(
        json.dumps(
            {
                "shield": "Shield 1 — Hardened Fine-Grained #OV PoW (STOC 2017 / CRYPTO 2018)",
                "parameters": {"n": chal.n, "d": chal.d, "min_secure_d": min_secure_dimension(chal.n)},
                "soundness_error_bound": f"{chal.soundness_error_bound:.3e}",
                "verified": ok,
                "server_issue_ms": round(t_issue_ms, 3),
                "client_solve_ms": round(t_solve_ms, 3),
                "server_verify_ms": round(t_verify_ms, 4),
            },
            indent=2,
        )
    )
