"""AutoPIL OpenAIAgentsGuard. See packages/core/autopil/openai_agents_guard.py for full docs."""

from __future__ import annotations
from functools import wraps
from typing import Any, Callable, Optional
from .guard import ContextGuard
from .models import SensitivityLevel


class OpenAIAgentsGuard(ContextGuard):
    """ContextGuard for OpenAI Agents SDK. Tags audit events with source_type='openai_agents'."""

    _source_type: str = "openai_agents"

    def function_tool(
        self,
        *,
        agent_role: str,
        user_id: str,
        source_id: str,
        sensitivity_level: SensitivityLevel = SensitivityLevel.MEDIUM,
        session_id: Optional[str] = None,
    ) -> Callable:
        """Decorator combining AutoPIL policy enforcement with @function_tool."""
        try:
            from agents import function_tool as openai_function_tool
        except ImportError as exc:
            raise ImportError("Install with: pip install openai-agents") from exc

        def decorator(fn: Callable) -> Any:
            protected = self.protect(
                agent_role=agent_role,
                user_id=user_id,
                source_id=source_id,
                sensitivity_level=sensitivity_level,
                session_id=session_id,
            )(fn)

            @openai_function_tool
            @wraps(fn)
            def tool_fn(*args: Any, **kwargs: Any) -> Any:
                return protected(*args, **kwargs)

            return tool_fn

        return decorator
