"""
Burrow adapter for OpenAI Agents SDK.

Provides input and output guardrails that scan messages with Burrow.

.. note:: Tool-level scanning limitation

    The OpenAI Agents SDK guardrails operate at the input/output level
    only — they see the full agent input or output text, but do **not**
    have access to individual ``tool_name`` or ``tool_args``. This is an
    architectural limitation of the Agents SDK guardrail system.

    For tool-level scanning, call ``guard.scan()`` directly inside your
    tool implementations::

        @function_tool
        def my_tool(query: str) -> str:
            result = guard.scan(query, content_type="tool_call", tool_name="my_tool")
            if result.is_blocked:
                return "Blocked by security policy."
            # ... tool logic ...

Usage:
    from burrow import BurrowGuard
    from burrow.integrations.openai_agents import create_burrow_guardrail

    guard = BurrowGuard(client_id="...", client_secret="...")
    burrow_rail = create_burrow_guardrail(guard)

    agent = Agent(
        name="my-agent",
        input_guardrails=[burrow_rail],
    )
"""

from __future__ import annotations

import logging
from typing import Any

from burrow import BurrowGuard

__all__ = [
    "create_burrow_guardrail",
    "create_burrow_output_guardrail",
]

logger = logging.getLogger("burrow.integrations.openai_agents")


def _make_guardrail_fn(
    guard: BurrowGuard,
    block_on_warn: bool,
    content_type: str,
    empty_reason: str,
):
    """Factory for guardrail functions that read agent.name from context."""
    try:
        from agents import GuardrailFunctionOutput
    except ImportError as exc:
        raise ImportError(
            "openai-agents is required for the OpenAI Agents adapter. "
            "Install it with: pip install burrow-sdk[openai-agents]"
        ) from exc

    async def guardrail_fn(ctx: Any, agent: Any, data: Any):
        text = str(data) if not isinstance(data, str) else data
        if not text.strip():
            return GuardrailFunctionOutput(
                output_info={"action": "allow", "reason": empty_reason},
                tripwire_triggered=False,
            )

        agent_name_resolved = "openai-agents"
        if hasattr(agent, "name") and agent.name:
            agent_name_resolved = f"openai-agents:{agent.name}"

        result = await guard.scan_async(
            text,
            content_type=content_type,
            agent=agent_name_resolved,
        )

        triggered = result.is_blocked or (block_on_warn and result.is_warning)

        return GuardrailFunctionOutput(
            output_info={
                "action": result.action,
                "category": result.category,
                "confidence": result.confidence,
                "request_id": result.request_id,
            },
            tripwire_triggered=triggered,
        )

    return guardrail_fn


def create_burrow_guardrail(
    guard: BurrowGuard,
    block_on_warn: bool = False,
):
    """
    Create an OpenAI Agents SDK input guardrail with per-agent identity.

    Automatically reads ``agent.name`` from the guardrail context to produce
    agent names like ``openai-agents:research-agent``.

    Args:
        guard: BurrowGuard instance.
        block_on_warn: If True, also trigger on "warn" verdicts.

    Returns:
        An InputGuardrail instance for the OpenAI Agents SDK.
    """
    try:
        from agents import input_guardrail
    except ImportError as exc:
        raise ImportError(
            "openai-agents is required for the OpenAI Agents adapter. "
            "Install it with: pip install burrow-sdk[openai-agents]"
        ) from exc

    fn = _make_guardrail_fn(guard, block_on_warn, "user_prompt", "empty input")
    return input_guardrail(fn)


def create_burrow_output_guardrail(
    guard: BurrowGuard,
    block_on_warn: bool = False,
):
    """
    Create an OpenAI Agents SDK output guardrail with per-agent identity.

    Automatically reads ``agent.name`` from the guardrail context.

    Args:
        guard: BurrowGuard instance.
        block_on_warn: If True, also trigger on "warn" verdicts.

    Returns:
        An OutputGuardrail instance for the OpenAI Agents SDK.
    """
    try:
        from agents import output_guardrail
    except ImportError as exc:
        raise ImportError(
            "openai-agents is required for the OpenAI Agents adapter. "
            "Install it with: pip install burrow-sdk[openai-agents]"
        ) from exc

    fn = _make_guardrail_fn(guard, block_on_warn, "tool_response", "empty output")
    return output_guardrail(fn)
