"""
A2A Agent Card Types
---------------------
Type definitions matching the A2A Protocol Agent Card specification.
"""

from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
from enum import Enum
import json


class A2AAuthType(str, Enum):
    """A2A authentication types."""
    NONE = "none"
    API_KEY = "api_key"
    OAUTH2 = "oauth2"
    BEARER = "bearer"
    LOCKSTOCK = "lockstock"  # Our custom auth type


@dataclass
class A2ASecurity:
    """A2A security configuration."""
    protocol: str = "LockStock-v1"
    auth_type: A2AAuthType = A2AAuthType.LOCKSTOCK
    verification_endpoint: Optional[str] = None
    public_key: Optional[str] = None
    signing_supported: bool = True

    def to_dict(self) -> Dict[str, Any]:
        return {
            "protocol": self.protocol,
            "auth_type": self.auth_type.value,
            "verification_endpoint": self.verification_endpoint,
            "public_key": self.public_key,
            "signing_supported": self.signing_supported
        }


@dataclass
class A2ACapability:
    """A2A capability definition."""
    name: str
    type: str = "lockstock_verified"
    description: Optional[str] = None
    input_schema: Optional[Dict[str, Any]] = None
    output_schema: Optional[Dict[str, Any]] = None

    def to_dict(self) -> Dict[str, Any]:
        result = {
            "name": self.name,
            "type": self.type
        }
        if self.description:
            result["description"] = self.description
        if self.input_schema:
            result["input_schema"] = self.input_schema
        if self.output_schema:
            result["output_schema"] = self.output_schema
        return result


@dataclass
class A2AAgentCard:
    """
    A2A Protocol Agent Card.

    This is the standard format for advertising agent capabilities
    in the A2A ecosystem.
    """

    # Required fields
    agent_id: str
    name: str

    # Optional metadata
    version: str = "1.0"
    description: Optional[str] = None
    provider: str = "LockStock"

    # Capabilities
    capabilities: List[A2ACapability] = field(default_factory=list)

    # Security
    security: Optional[A2ASecurity] = None

    # Endpoints
    task_endpoint: Optional[str] = None
    status_endpoint: Optional[str] = None

    # Additional metadata
    metadata: Dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        """Convert to A2A Agent Card JSON format."""
        return {
            "version": self.version,
            "metadata": {
                "id": self.agent_id,
                "name": self.name,
                "description": self.description or f"LockStock-secured agent: {self.name}",
                "provider": self.provider,
                **self.metadata
            },
            "capabilities": [cap.to_dict() for cap in self.capabilities],
            "security": self.security.to_dict() if self.security else None,
            "endpoints": {
                "task": self.task_endpoint,
                "status": self.status_endpoint
            }
        }

    def to_json(self, indent: int = 2) -> str:
        """Convert to JSON string."""
        return json.dumps(self.to_dict(), indent=indent)

    @classmethod
    def from_lockstock_card(
        cls,
        lockstock_card: Dict[str, Any],
        endpoint: str = "https://lockstock-api-i9kp.onrender.com"
    ) -> "A2AAgentCard":
        """
        Create an A2A Agent Card from a LockStock agent card.

        Args:
            lockstock_card: LockStock internal agent card
            endpoint: LockStock API endpoint

        Returns:
            A2A-compatible agent card
        """
        agent_id = lockstock_card.get("agent_id", "unknown")

        # Convert LockStock capabilities to A2A capabilities
        capabilities = [
            A2ACapability(
                name=cap,
                type="lockstock_verified",
                description=f"Cryptographically verified capability: {cap}"
            )
            for cap in lockstock_card.get("capabilities", [])
        ]

        # Create security configuration
        security = A2ASecurity(
            protocol="LockStock-v1",
            auth_type=A2AAuthType.LOCKSTOCK,
            verification_endpoint=f"{endpoint}/verify",
            public_key=lockstock_card.get("public_key"),
            signing_supported=True
        )

        return cls(
            agent_id=agent_id,
            name=lockstock_card.get("display_name", agent_id),
            description=lockstock_card.get("description"),
            capabilities=capabilities,
            security=security,
            task_endpoint=f"{endpoint}/a2a/task",
            status_endpoint=f"{endpoint}/a2a/status/{agent_id}",
            metadata={
                "fingerprint": lockstock_card.get("fingerprint"),
                "owner_id": lockstock_card.get("owner_id"),
                "created_at": lockstock_card.get("created_at"),
                "status": lockstock_card.get("status", "active")
            }
        )
