"""TEYGU Shield v1.6 — Seviye 2: Python / FastAPI Kritik İşlem Koruma Kapısı.

Özellikler:
- Gerçek non-blocking `async def evaluate_with_shield(...)` (FastAPI event-loop'u asla dondurmaz).
- Harici paket gerektirmeyen standart kütüphane `HMAC-SHA256` (`X-Teygu-Client-Mac`) imzalama.
- Kritik para çıkışı için varsayılan `fail_open_on_unavailable=False` (fail-closed);
  salt-okunur veya gölge pilot uçları için `fail_open_on_unavailable=True` seçeneği.
"""

from __future__ import annotations

import asyncio
import hashlib
import hmac
import json
import urllib.error
import urllib.request
from typing import Any


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


_shield_client = urllib.request.build_opener(_NoRedirect())


def compute_client_mac_hex(client_hmac_key_hex: str, raw_body: bytes) -> str:
    key = bytes.fromhex(client_hmac_key_hex.strip())
    return hmac.new(key, raw_body, hashlib.sha256).hexdigest()


def evaluate_with_shield_sync(
    intent: dict[str, Any],
    action: dict[str, Any],
    shield_url: str = "http://127.0.0.1:8910",
    client_hmac_key_hex: str | None = None,
    timeout_sec: float = 1.5,
    fail_open_on_unavailable: bool = False,
) -> dict[str, Any]:
    body = json.dumps({"intent": intent, "action": action}, separators=(",", ":")).encode("utf-8")
    headers = {"Content-Type": "application/json"}
    if client_hmac_key_hex:
        headers["X-Teygu-Client-Mac"] = compute_client_mac_hex(client_hmac_key_hex, body)

    req = urllib.request.Request(
        f"{shield_url.rstrip('/')}/v1/evaluate",
        data=body,
        headers=headers,
        method="POST",
    )
    try:
        with _shield_client.open(req, timeout=timeout_sec) as resp:
            if resp.status != 200 or resp.headers.get_all("X-Teygu-Decision") != ["allow"]:
                raise PermissionError("TEYGU Shield did not issue an enforce-mode permit")
            data = json.loads(resp.read().decode("utf-8"))
            permit = data.get("execution_permit")
            if data.get("allowed") is not True or not isinstance(permit, dict) or permit.get("shadow_only") is not False:
                raise PermissionError(f"TEYGU Shield blocked: {data.get('violations')}")
            return data
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", errors="replace")
        raise PermissionError(f"TEYGU Shield rejected ({exc.code}): {detail}") from exc
    except (urllib.error.URLError, TimeoutError) as exc:
        if fail_open_on_unavailable:
            return {"allowed": True, "decision": "FAIL_OPEN_FALLBACK", "error": str(exc)}
        raise ConnectionError(f"TEYGU Shield unreachable (fail-closed): {exc}") from exc


async def evaluate_with_shield(
    intent: dict[str, Any],
    action: dict[str, Any],
    shield_url: str = "http://127.0.0.1:8910",
    client_hmac_key_hex: str | None = None,
    timeout_sec: float = 1.5,
    fail_open_on_unavailable: bool = False,
) -> dict[str, Any]:
    return await asyncio.to_thread(
        evaluate_with_shield_sync,
        intent,
        action,
        shield_url,
        client_hmac_key_hex,
        timeout_sec,
        fail_open_on_unavailable,
    )
