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

Implements a Ball-Rosen-Sabin-Vasudevan (STOC 2017) style Fine-Grained Proof-of-Work
over the 127-bit Mersenne prime field F_p (p = 2^127 - 1) anchored to counting
Orthogonal Vectors (`pOV`):

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

Why This Complements Shields 0, 2, and 3:
  - Zero SHA-256 / zero one-way function assumptions (survives hash breaks and any
    galactic or high/moderate-degree P = NP solver whose circuit exponent alpha >= 2).
  - Zero Google reCAPTCHA (Node 0 Human Dignity: zero resident tracking/PII leaks).
  - Multi-client anti-intersection hardening: each challenge applies a fresh exact
    pOV-preserving automorphism (random row permutations pi_U, pi_V, column permutation
    pi_c, and reciprocal column scaling alpha_l / alpha_l^-1) + double blinding
    U(t) = U_tilde + (t - r*) R_U, V(t) = V_tilde + (t - r*) R_V + automatic epoch rotation.
  - Exact Schwartz-Zippel soundness over F_(2^127 - 1): any forged degree-(2d) polynomial
    passes g(r*) == y* with probability <= 2d / (2^127 - 1 - (2d + 1)) < 10^-35.
  - Real defender asymmetry: Server verifies in O(d^2) microseconds while a Sybil bot
    flooding requests must pay Theta(d^2 * n^2) work per submission.
"""

from __future__ import annotations

import json
import secrets
import time
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 is malformed."""


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:
    """
    Exact evaluation of the Ball-Rosen-Sabin-Vasudevan Orthogonal-Vectors polynomial:
        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(n^2 * d) arithmetic operations over F_(2^127 - 1).
    """
    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 apply_pov_automorphism(
    u_mat: Matrix,
    v_mat: Matrix,
) -> Tuple[Matrix, Matrix]:
    """
    Apply a fresh random 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
    Guarantees pOV(U_tilde, V_tilde) == pOV(U, V) mod p identically while ensuring
    successive blinded challenge lines remain skew in F_p^(2*n*d).
    """
    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 O(n*d) #OV polynomial curve challenge issued to a client."""

    challenge_id: str
    n: int
    d: int
    num_eval_points: int  # 2*d + 1 points (degree of pOV(U(t), V(t)) is at most 2*d)
    u0: Matrix
    r_u: Matrix
    v0: Matrix
    r_v: Matrix
    soundness_error_bound: float
    attestation: str = "probabilistic_structural"


@dataclass(frozen=True)
class FineGrainedSolution:
    """Compact solution returned by the client: only 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) arithmetic work over F_(2^127 - 1).
    """
    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:
    """
    Server-side issuer and O(d^2) microsecond verifier for Ball-Rosen-Sabin-Vasudevan
    #OV Fine-Grained Proof-of-Work.
    """

    def __init__(
        self,
        n: int = 36,
        d: int = 4,
        epoch_max_challenges: int = 64,
    ) -> None:
        if n < 4 or d < 2:
            raise ValueError("FineGrainedOvIssuer requires n >= 4 and d >= 2.")
        if epoch_max_challenges < 1:
            raise ValueError("epoch_max_challenges must be >= 1.")
        self.n = n
        self.d = d
        self.epoch_max_challenges = epoch_max_challenges
        self._epoch_id = 0
        self._epoch_uses = 0
        self._u_star: Matrix = ()
        self._v_star: Matrix = ()
        self._y_star: int = 0
        # Active single-use secret verification records: challenge_id -> (r_star, expected_y_star)
        self._pending: Dict[str, Tuple[int, int]] = {}
        self._burned_ids: set[str] = set()
        self._rotate_epoch()

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

    @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 _rotate_epoch(self) -> None:
        self._epoch_id += 1
        self._epoch_uses = 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)."""
        if self._epoch_uses >= self.epoch_max_challenges:
            self._rotate_epoch()
        self._epoch_uses += 1

        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)

        # Sample secret r* strictly outside evaluation set {1, ..., 2*d + 1}
        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(6).upper()}"
        self._pending[chal_id] = (r_star, self._y_star)
        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,
        )

    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).
        """
        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 = self._pending.pop(cid)
        self._burned_ids.add(cid)

        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."
            )
        return True


class ObbSanctuaryPowGate:
    """
    Zero-CAPTCHA, Zero-PII public civic admission gate combining:
      - Shield 1: FineGrainedOvIssuer (blocks Sybil bots without Google reCAPTCHA or SHA-256)
      - Node 0:   ObbSafetyFloor (hard-blocks forbidden resident PII)
      - Node 1:   SweetbrierEpistemicGate (3-valued K3/B4 truth lattice + LeCun Firewall)
    """

    def __init__(
        self,
        node_id: str,
        n: int = 36,
        d: int = 4,
        epoch_max_challenges: int = 64,
    ) -> None:
        self.issuer = FineGrainedOvIssuer(n=n, d=d, epoch_max_challenges=epoch_max_challenges)
        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:
        """Require valid Fine-Grained #OV PoW before admitting a public form into Node 0/1."""
        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=40, d=4, epoch_max_challenges=64)

    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()
    verified = issuer.verify_solution(sol)
    t_verify_ms = (time.perf_counter() - t2) * 1000.0

    print(
        json.dumps(
            {
                "attestation": "probabilistic_structural",
                "shield": "Shield 1 — Fine-Grained #OV Proof-of-Work (Ball-Rosen-Sabin-Vasudevan STOC 2017)",
                "parameters": {"n": chal.n, "d": chal.d, "eval_points_2d_plus_1": chal.num_eval_points},
                "sha256_or_captcha_used": False,
                "soundness_error_bound": f"{chal.soundness_error_bound:.3e}",
                "verified": verified,
                "server_issue_ms": round(t_issue_ms, 3),
                "client_solve_ms": round(t_solve_ms, 3),
                "server_verify_ms": round(t_verify_ms, 4),
                "client_to_server_verify_speedup_x": round(t_solve_ms / max(t_verify_ms, 1e-6), 1),
            },
            indent=2,
        )
    )
