#!/usr/bin/env python3
"""
ONE BIG BACKEND — LAYER 1: NIIS X-ROAD REST EPISTEMIC SIDECAR (`obb_xroad_epistemic_sidecar.py`)
License: GNU AGPLv3
External Dependencies: 0 (100% Python Standard Library + local `obb_primitives` & `obb_epistemic_lattice`)

ARCHITECTURAL DESIGN (v2 — Retiring the v1 Symmetric-HMAC Central-Directory Mock):
  NIIS X-Road already provides a battle-tested, MIT-licensed Security Server handling
  asymmetric non-repudiation (PKCS#11 HSM, X.509/OCSP, mTLS, ASiC-E signed message containers,
  and RFC-3161 TSA timestamping) plus an active NIST PQC migration track.

  What X-Road does NOT inspect is the *epistemic status* of an AI-generated payload before
  a member's Security Server signs and transmits it: an autonomous agent can push an
  unconfirmed hallucination (`confirmed=1`) or leak forbidden resident PII inside a validly
  signed X-Road REST request.

  This zero-dependency sidecar sits directly between an organization's internal app/agent
  and its local NIIS X-Road Security Server REST proxy:
      [AI Agent / App] -> [XRoadEpistemicSidecar (Layer 0)] -> [Real NIIS Security Server /r1/...]

  It NEVER stores or handles member signing keys (zero weakening of X-Road non-repudiation).
  Instead, it validates authentic NIIS REST headers (`X-Road-Client`, `X-Road-Service`,
  `X-Road-Id`), enforces Node 0 Zero-PII + Belnap B4 + LLM Source Clamp, stamps explicit
  epistemic provenance headers (`X-Sweetbrier-Truth`, `X-Sweetbrier-Claim-Hash`), and logs
  local 1-Click atomic rollback snapshots.
"""

from __future__ import annotations

import json
import re
import uuid
from dataclasses import dataclass
from typing import Any, Dict, Mapping, Optional, Tuple

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

# Authentic NIIS X-Road 4-part subsystem identifier: INSTANCE/CLASS/MEMBER_CODE/SUBSYSTEM
XROAD_SUBSYSTEM_RE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$")
# Authentic NIIS X-Road REST path: /r1/{instance}/{class}/{member}/{subsystem}/{serviceCode}[/...]
XROAD_REST_PATH_RE = re.compile(
    r"^/r1/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)(/.*)?$"
)


class XRoadSidecarPolicyError(PermissionError):
    """Raised when an outbound or inbound X-Road REST request fails header or epistemic policy."""


@dataclass(frozen=True)
class XRoadRestRequest:
    """Minimal representation of a real NIIS X-Road Security Server REST request."""

    method: str
    path: str
    headers: Mapping[str, str]
    json_body: Mapping[str, Any]


@dataclass(frozen=True)
class SidecarDecision:
    allowed: bool
    lane: str  # "FINALIZED" | "STAGED_UNCONFIRMED" | "BLOCKED"
    claim: Optional[EpistemicClaim]
    forwarded_request: Optional[XRoadRestRequest]
    snapshot: Optional[StateSnapshot]
    reason: str


class XRoadEpistemicSidecar:
    """
    Zero-dependency epistemic & Zero-PII policy sidecar sitting in front of a real
    NIIS X-Road Security Server REST endpoint (`http://localhost:8080/r1/...`).
    """

    def __init__(
        self,
        local_client_subsystem: str,
        allow_staged_egress: bool = True,
    ) -> None:
        if not XROAD_SUBSYSTEM_RE.match(local_client_subsystem):
            raise ValueError(
                f"Invalid NIIS X-Road subsystem identifier '{local_client_subsystem}' "
                f"(expected INSTANCE/CLASS/MEMBER/SUBSYSTEM)."
            )
        self.local_client_subsystem = local_client_subsystem
        self.allow_staged_egress = allow_staged_egress
        self.safety_floor = ObbSafetyFloor()
        self.epistemic_gate = SweetbrierEpistemicGate(
            node_id=local_client_subsystem,
            safety_floor=self.safety_floor,
        )

    @staticmethod
    def parse_rest_target(path: str) -> Tuple[str, str]:
        """Extract `(provider_subsystem, service_code)` from an authentic NIIS `/r1/...` path."""
        m = XROAD_REST_PATH_RE.match(path)
        if not m:
            raise XRoadSidecarPolicyError(
                f"Path '{path}' does not conform to NIIS X-Road REST format "
                f"'/r1/{{instance}}/{{class}}/{{member}}/{{subsystem}}/{{serviceCode}}'."
            )
        provider = f"{m.group(1)}/{m.group(2)}/{m.group(3)}/{m.group(4)}"
        service_code = m.group(5)
        return provider, service_code

    def filter_outbound_rest(
        self,
        req: XRoadRestRequest,
        subject: str,
        source_kind: SourceKind,
        source_id: str,
        proposed_truth: EpistemicTruth,
        require_verified: bool = True,
    ) -> SidecarDecision:
        """
        Gate an outbound REST call BEFORE it reaches the local NIIS X-Road Security Server:
          1. Validates `X-Road-Client` matches `local_client_subsystem` and path is valid `/r1/...`.
          2. Enforces Node 0 Zero-PII Floor on `req.json_body`.
          3. Runs Layer 0 Belnap B4 + LLM Source Clamp (clamping LLM self-certified VERIFIED -> UNKNOWN).
          4. Blocks unverified writes if `require_verified=True`; otherwise explicitly tags
             the forwarded REST headers with `X-Sweetbrier-Truth: UNKNOWN` so the receiving
             Security Server / subsystem knows the draft is unconfirmed.
        """
        headers_ci = {k.lower(): v for k, v in req.headers.items()}
        xroad_client = headers_ci.get("x-road-client", "")
        if xroad_client != self.local_client_subsystem:
            raise XRoadSidecarPolicyError(
                f"X-Road-Client header '{xroad_client}' does not match local subsystem "
                f"'{self.local_client_subsystem}'."
            )
        provider_subsystem, service_code = self.parse_rest_target(req.path)
        xroad_id = headers_ci.get("x-road-id") or str(uuid.uuid4())

        # Node 0 + Layer 0 ingestion
        try:
            claim = self.epistemic_gate.ingest(
                claim_id=xroad_id,
                subject=subject,
                payload=req.json_body,
                proposed_truth=proposed_truth,
                source_kind=source_kind,
                source_id=source_id,
                note=f"Outbound NIIS X-Road REST {req.method} -> {provider_subsystem}/{service_code}",
            )
        except SafetyFloorViolationError as exc:
            return SidecarDecision(
                allowed=False,
                lane="BLOCKED",
                claim=None,
                forwarded_request=None,
                snapshot=None,
                reason=str(exc),
            )

        # If caller requires VERIFIED (production write endpoint), block anything else
        if require_verified and claim.truth_value is not EpistemicTruth.VERIFIED:
            snap = self.epistemic_gate.stage_unconfirmed(f"BLOCKED_EGRESS:{service_code}", claim)
            return SidecarDecision(
                allowed=False,
                lane="STAGED_UNCONFIRMED",
                claim=claim,
                forwarded_request=None,
                snapshot=snap,
                reason=(
                    f"Blocked from FINALIZED X-Road egress: truth={claim.truth_value.value}, "
                    f"llm_clamped={claim.llm_clamped}. Quarantined locally for human confirmation."
                ),
            )

        if not self.allow_staged_egress and claim.truth_value is EpistemicTruth.UNKNOWN:
            return SidecarDecision(
                allowed=False,
                lane="BLOCKED",
                claim=claim,
                forwarded_request=None,
                snapshot=None,
                reason="Staged UNKNOWN egress disabled by local sidecar policy.",
            )

        lane = "FINALIZED" if claim.truth_value is EpistemicTruth.VERIFIED else "STAGED_UNCONFIRMED"
        snap = (
            self.epistemic_gate.commit_verified(f"XROAD_OUT:{service_code}", claim)
            if lane == "FINALIZED"
            else self.epistemic_gate.stage_unconfirmed(f"XROAD_OUT_STAGED:{service_code}", claim)
        )

        # Preserve authentic NIIS headers and append explicit epistemic provenance metadata
        out_headers: Dict[str, str] = dict(req.headers)
        out_headers["X-Road-Client"] = self.local_client_subsystem
        out_headers["X-Road-Id"] = xroad_id
        out_headers["X-Sweetbrier-Truth"] = claim.truth_value.value
        out_headers["X-Sweetbrier-Source-Kind"] = claim.source_kind.value
        out_headers["X-Sweetbrier-Claim-Hash"] = claim.claim_hash
        out_headers["X-Sweetbrier-Lane"] = lane

        forwarded = XRoadRestRequest(
            method=req.method,
            path=req.path,
            headers=out_headers,
            json_body=req.json_body,
        )
        return SidecarDecision(
            allowed=True,
            lane=lane,
            claim=claim,
            forwarded_request=forwarded,
            snapshot=snap,
            reason=f"Cleared for local NIIS Security Server signing ({lane}).",
        )


if __name__ == "__main__":
    sidecar = XRoadEpistemicSidecar("US-VA-ROA/NGO/rescue-mission/intake")
    req = XRoadRestRequest(
        method="POST",
        path="/r1/US-VA-ROA/NGO/council-community-services/shelter-sync/updateCapacity",
        headers={"X-Road-Client": "US-VA-ROA/NGO/rescue-mission/intake"},
        json_body={"site": "Rescue Mission SE", "beds_open_aggregate": 6, "pii_bytes": 0},
    )
    blocked = sidecar.filter_outbound_rest(
        req=req,
        subject="capacity:rescue-mission",
        source_kind=SourceKind.LLM_SYNTHESIS,
        source_id="intake_agent_v4",
        proposed_truth=EpistemicTruth.VERIFIED,
        require_verified=True,
    )
    cleared = sidecar.filter_outbound_rest(
        req=req,
        subject="capacity:rescue-mission",
        source_kind=SourceKind.HUMAN_ATTESTED,
        source_id="shift_supervisor",
        proposed_truth=EpistemicTruth.VERIFIED,
        require_verified=True,
    )
    print(
        json.dumps(
            {
                "llm_self_certified_allowed": blocked.allowed,
                "llm_clamped_truth": blocked.claim.truth_value.value if blocked.claim else None,
                "human_attested_allowed": cleared.allowed,
                "forwarded_headers": dict(cleared.forwarded_request.headers)
                if cleared.forwarded_request
                else None,
            },
            indent=2,
        )
    )
