from abc import ABC, abstractmethod
from enum import Enum
from typing import Any, Optional
from pydantic import BaseModel, Field


class ChannelType(str, Enum):
    TELEGRAM = "telegram"
    DISCORD = "discord"
    WEBHOOK = "webhook"


class ChannelButton(BaseModel):
    text: str
    action_type: str = Field(default="url", description="'url' or 'callback'")
    value: str


class ChannelMessageRequest(BaseModel):
    recipient_id: str = Field(description="Telegram chat_id, Discord channel_id, or webhook endpoint")
    text: str
    parse_mode: str = Field(default="HTML", description="'HTML', 'MarkdownV2', or 'plain'")
    buttons: list[list[ChannelButton]] = Field(default_factory=list)
    media_type: Optional[str] = None
    media_url: Optional[str] = None
    extra_metadata: dict[str, Any] = Field(default_factory=dict)


class ChannelMessageResult(BaseModel):
    success: bool
    channel: ChannelType
    message_id: Optional[str] = None
    delivered_at: Optional[str] = None
    raw_response: dict[str, Any] = Field(default_factory=dict)
    error_message: Optional[str] = None


class BaseChannelAdapter(ABC):
    @property
    @abstractmethod
    def channel_type(self) -> ChannelType:
        """Returns the channel identifier."""
        pass

    @abstractmethod
    async def send_message(self, request: ChannelMessageRequest) -> ChannelMessageResult:
        """Dispatches an outbound message to the target platform channel."""
        pass

    @abstractmethod
    async def verify_webhook_signature(
        self, headers: dict[str, str], body: bytes, secret: str
    ) -> bool:
        """Verifies cryptographic authenticity of inbound channel webhooks."""
        pass

    @abstractmethod
    async def normalize_incoming_event(self, raw_payload: dict[str, Any]) -> dict[str, Any]:
        """Normalizes heterogeneous channel updates into standard internal event dict."""
        pass
