"""
ID Wispera OpenAI Agents SDK Integration
Credential provider for the OpenAI Agents SDK

Manages API keys for agent initialization, tool credential injection,
and multi-agent handoffs with scoped credentials.

Usage:
    from id_wispera.integrations.openai_agents import WisperaOpenAIAgentProvider

    provider = WisperaOpenAIAgentProvider()
    api_key = provider.get_agent_key("coding-agent")
"""

from typing import Optional, Any
from id_wispera.integrations.base import WisperaBaseProvider


class WisperaOpenAIAgentProvider(WisperaBaseProvider):
    """
    OpenAI Agents SDK credential provider.
    Manages governed credentials for OpenAI agents, tools, and handoffs.
    """

    def __init__(
        self,
        vault_path: Optional[str] = None,
        passphrase: Optional[str] = None,
        passphrase_env: str = "IDW_PASSPHRASE",
    ):
        super().__init__(
            vault_path=vault_path,
            passphrase=passphrase,
            passphrase_env=passphrase_env,
            actor="openai-agents",
        )

    def get_agent_key(self, passport_name: str = "openai") -> str:
        """
        Get an API key for agent initialization.

        Args:
            passport_name: Name of the passport containing the key

        Returns:
            The API key string
        """
        return self.get(
            passport_name,
            platform="openai",
            purpose="Agent initialization",
        )

    def get_agent_config(
        self,
        passport_name: str = "openai",
        model: Optional[str] = None,
    ) -> dict[str, Any]:
        """
        Get OpenAI-specific agent configuration.

        Args:
            passport_name: Name of the passport
            model: Optional model name (defaults to gpt-4)

        Returns:
            Configuration dict with api_key, model, and provider
        """
        config = self.get_llm_config(passport_name, model)
        if "model" not in config:
            config["model"] = "gpt-4"
        config["provider"] = "openai"
        return config

    def get_tool_auth(
        self,
        tool_passport_name: str,
        header_name: str = "Authorization",
        header_template: Optional[str] = None,
    ) -> dict[str, str]:
        """
        Get credentials for a tool that the agent will use.

        Args:
            tool_passport_name: Name of the passport for the tool
            header_name: HTTP header name (default: Authorization)
            header_template: Header value template (default: Bearer {value})

        Returns:
            Dict with tool, credential, header_name, header_template
        """
        value = self.get(
            tool_passport_name,
            purpose=f"Tool authentication for {tool_passport_name}",
        )

        return {
            "tool": tool_passport_name,
            "credential": value,
            "header_name": header_name,
            "header_template": header_template or f"Bearer {value}",
        }

    def get_handoff_credential(
        self,
        passport_name: str,
        target_agent: str,
        allowed_scopes: Optional[list[str]] = None,
    ) -> str:
        """
        Get scoped credentials for an agent handoff.

        Args:
            passport_name: Name of the passport
            target_agent: Name of the target agent
            allowed_scopes: Scopes the target agent is allowed

        Returns:
            The credential value

        Raises:
            ValueError: If scope is not permitted
        """
        passport = self._get_passport(passport_name, platform="openai")

        if allowed_scopes:
            passport_scopes = passport.scope if hasattr(passport, "scope") else []
            if not all(s in passport_scopes for s in allowed_scopes):
                raise ValueError(
                    f"Scope not permitted for handoff to {target_agent}. "
                    f"Requested: {allowed_scopes}, Available: {passport_scopes}"
                )

        self._log_access_entry(
            passport.id,
            "openai",
            f"Handoff to agent: {target_agent}",
        )

        return passport.credential_value

    def get_tool_credentials(
        self,
        tool_passport_map: dict[str, str],
    ) -> dict[str, str]:
        """
        Get multiple tool credentials at once.

        Args:
            tool_passport_map: Mapping of tool_name -> passport_name

        Returns:
            Mapping of tool_name -> credential_value
        """
        results = {}
        for tool_name, passport_name in tool_passport_map.items():
            results[tool_name] = self.get(
                passport_name,
                purpose=f"Tool credential for {tool_name}",
            )
        return results
