"""Vigil runtime integration. Install aiohttp; set VIGIL_API_KEY.
The key identifies the agent. Stop on block, timeout, HTTP errors or invalid verdicts.
Use redacted_input before the model and redacted_output before releasing its answer.
Check planned tools BEFORE invoking them: recording a trace cannot undo an action.
"""
import asyncio
import json
import os
import re
from typing import Any
import aiohttp


class SecurityViolationError(RuntimeError):
    """The check blocked execution or failed to produce a valid verdict."""


_TOOL_ARG_RULES = [
    ("Destructive shell command", re.compile(r"\b(rm\s+-[a-z]*[rf][a-z]*\s+[/~*]|mkfs(\.\w+)?\s|dd\s+if=|shutdown\s+-[hr]|chmod\s+-R\s+777\s+/)", re.I)),
    ("Remote download piped to a shell", re.compile(r"\b(curl|wget)\b[^|\n]{0,300}\|\s*(ba|z)?sh\b", re.I)),
    ("Destructive SQL statement", re.compile(r"\b(drop\s+(table|database|schema)|truncate\s+table|alter\s+table\s+\S+\s+drop)\b", re.I)),
    ("SQL injection pattern", re.compile(r"('|\")\s*(or|and)\s+('|\")?\d+('|\")?\s*=\s*('|\")?\d+|;\s*--|\bunion\s+(all\s+)?select\b", re.I)),
    ("Path traversal or sensitive file", re.compile(r"(\.\.[/\\]){2,}|/etc/(passwd|shadow)|(^|[/\\])\.(env|ssh[/\\]|aws[/\\]credentials)\b", re.I)),
    ("Cloud metadata endpoint", re.compile(r"169\.254\.169\.254|metadata\.google\.internal", re.I)),
]


def validate_tool_arguments(tool_name: str, tool_args: Any) -> None:
    """Local, deterministic pre-execution check (no network). Raises on dangerous arguments.
    Also send planned tool_calls to post_execution_check for the full server-side policy."""
    text = tool_args if isinstance(tool_args, str) else json.dumps(tool_args, default=str)
    hits = [label for label, rule in _TOOL_ARG_RULES if rule.search(text[:50_000])]
    if hits:
        raise SecurityViolationError(f"Tool '{tool_name}' blocked: " + "; ".join(hits))


class VigilClient:
    def __init__(self, api_key: str, base_url: str = "https://vigiltrism.ai/api/public/v1", timeout: float = 10):
        if not api_key.strip():
            raise ValueError("A Vigil agent API key is required")
        self.base_url = base_url.rstrip("/")
        self.headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
        self.timeout = aiohttp.ClientTimeout(total=timeout)

    async def _post(self, path: str, payload: dict[str, Any], expected_status: int) -> dict[str, Any]:
        try:
            async with aiohttp.ClientSession(timeout=self.timeout) as session:
                async with session.post(f"{self.base_url}/{path}", json=payload, headers=self.headers) as response:
                    if response.status != expected_status:
                        # Do not echo response bodies: they may contain sensitive data.
                        raise SecurityViolationError(f"Vigil check failed (HTTP {response.status})")
                    result = await response.json()
        except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as error:
            raise SecurityViolationError("Vigil check unavailable or invalid; execution halted") from error
        if not isinstance(result, dict) or result.get("decision") not in ("allow", "flag", "block"):
            raise SecurityViolationError("Invalid Vigil decision; execution halted")
        if result["decision"] == "block":
            violations = result.get("violations")
            reasons = [v["message"] for v in violations if isinstance(v, dict) and isinstance(v.get("message"), str)] if isinstance(violations, list) else []
            raise SecurityViolationError("Execution halted by Vigil: " + ("; ".join(reasons) or "Security policy violation"))
        return result

    async def pre_flight_check(self, prompt_input: str, retrieved_docs: list[str] | None = None, trace_id: str | None = None) -> dict[str, Any]:
        payload: dict[str, Any] = {"input": prompt_input, "retrieved_documents": [{"content": doc} for doc in (retrieved_docs or [])]}
        if trace_id:
            payload["trace_id"] = trace_id
        return await self._post("scan", payload, 200)

    async def post_execution_check(self, prompt_input: str, output: str, tool_calls: list[dict[str, Any]] | None = None, trace_id: str | None = None) -> dict[str, Any]:
        payload: dict[str, Any] = {"input": prompt_input, "output": output, "tool_calls": tool_calls or []}
        if trace_id:
            payload["trace_id"] = trace_id
        return await self._post("executions", payload, 201)


async def main():
    vigil = VigilClient(os.environ["VIGIL_API_KEY"])
    try:
        verdict = await vigil.pre_flight_check("Hello from my agent", ["Public FAQ: Welcome to Vigil."])
        print("Pre-flight accepted:", verdict["decision"])
        # Invoke your model with verdict.get("redacted_input") ?? original input.
        # Before running any tool, validate its arguments locally (fails closed):
        validate_tool_arguments("execute_sql_query", {"query": "SELECT name FROM users WHERE id = 1"})
    except SecurityViolationError as error:
        print(f"[HALTED] {error}")
        raise SystemExit(1) from error


if __name__ == "__main__":
    asyncio.run(main())
