"""
ID Wispera Google A2A Protocol Integration
Passport-backed identity for Google's Agent-to-Agent protocol

Provides:
- Agent Card credential population from vault passports
- Incoming agent authentication validation
- Task-scoped credential access

Usage:
    from id_wispera.integrations.google_a2a import WisperaA2AProvider

    provider = WisperaA2AProvider()
    creds = provider.get_agent_credentials("my-agent")
"""

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


class WisperaA2AProvider(WisperaBaseProvider):
    """
    Google A2A protocol credential provider.
    Manages passport-backed identity for agent-to-agent communication.
    """

    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="google-a2a",
        )

    def get_agent_credentials(self, passport_name: str) -> dict[str, Any]:
        """
        Get credentials for populating an A2A Agent Card.

        Args:
            passport_name: Name of the passport

        Returns:
            Dict with auth_token, agent_id, scopes, and expires_at
        """
        passport = self._get_passport(passport_name, platform="google-a2a")

        self._log_access_entry(
            passport.id,
            "google-a2a",
            "A2A Agent Card credential population",
        )

        return {
            "auth_token": passport.credential_value,
            "agent_id": getattr(passport, "agent_id", None) or passport.name,
            "scopes": getattr(passport, "scope", []),
            "expires_at": getattr(passport, "valid_until", None),
        }

    def validate_agent_auth(
        self,
        token: str,
        expected_agent_id: Optional[str] = None,
    ) -> dict[str, Any]:
        """
        Validate an incoming agent's authentication token.

        Args:
            token: The authentication token to validate
            expected_agent_id: Optional expected agent ID

        Returns:
            Dict with valid (bool), agent_id (str), and error (str)
        """
        try:
            available = self.list_available(platform="google-a2a")

            for name in available:
                try:
                    passport = self._get_passport(name, platform="google-a2a")
                    if passport.credential_value == token:
                        agent_id = getattr(passport, "agent_id", None) or passport.name

                        if expected_agent_id and agent_id != expected_agent_id:
                            return {"valid": False, "error": "Agent ID mismatch"}

                        self._log_access_entry(
                            passport.id,
                            "google-a2a",
                            f"A2A auth validation for agent: {agent_id}",
                        )

                        return {"valid": True, "agent_id": agent_id}
                except Exception:
                    continue

            return {"valid": False, "error": "Token not found in vault"}

        except Exception as e:
            return {"valid": False, "error": str(e)}

    def get_task_credentials(
        self,
        task_id: str,
        required_scopes: list[str],
        passport_names: list[str],
    ) -> dict[str, Any]:
        """
        Get credentials scoped for a specific A2A task.

        Args:
            task_id: The task identifier
            required_scopes: Scopes required for the task
            passport_names: Passports to check

        Returns:
            Dict with credentials, task_id, and scopes
        """
        credentials = {}

        for name in passport_names:
            passport = self._get_passport(name, platform="google-a2a")
            passport_scopes = getattr(passport, "scope", [])

            if all(s in passport_scopes for s in required_scopes):
                self._log_access_entry(
                    passport.id,
                    "google-a2a",
                    f"A2A task {task_id}: credential access",
                )
                credentials[name] = passport.credential_value

        return {
            "credentials": credentials,
            "task_id": task_id,
            "scopes": required_scopes,
        }

    def get_google_cloud_key(self, passport_name: str = "google-cloud") -> str:
        """Get a Google Cloud API key for A2A service calls."""
        return self.get(
            passport_name,
            platform="google-a2a",
            purpose="Google Cloud API access via A2A",
        )
