import hmac
import hashlib
from typing import Any, Optional
from datetime import datetime, timezone
import httpx
from modules.channels.base import (
    BaseChannelAdapter,
    ChannelType,
    ChannelMessageRequest,
    ChannelMessageResult,
)


class DiscordChannelAdapter(BaseChannelAdapter):
    """
    Channel adapter for Discord Bot & Webhook integrations.
    Supports sending rich embeds, action row buttons, and normalizing Discord interaction payloads.
    """

    def __init__(self, bot_token: Optional[str] = None):
        self.bot_token = bot_token

    @property
    def channel_type(self) -> ChannelType:
        return ChannelType.DISCORD

    async def send_message(self, request: ChannelMessageRequest) -> ChannelMessageResult:
        try:
            # If recipient_id is a full webhook URL, post directly
            is_webhook_url = request.recipient_id.startswith("http://") or request.recipient_id.startswith("https://")
            
            payload: dict[str, Any] = {"content": request.text}
            
            # Convert buttons to Discord Components (Action Rows)
            if request.buttons:
                action_rows = []
                for row in request.buttons:
                    components = []
                    for b in row:
                        if b.action_type == "url":
                            components.append({
                                "type": 2,  # Button component
                                "style": 5,  # Link style
                                "label": b.text,
                                "url": b.value,
                            })
                        else:
                            components.append({
                                "type": 2,
                                "style": 1,  # Primary style
                                "label": b.text,
                                "custom_id": b.value,
                            })
                    if components:
                        action_rows.append({"type": 1, "components": components})
                payload["components"] = action_rows

            if is_webhook_url:
                async with httpx.AsyncClient(timeout=10.0) as client:
                    resp = await client.post(request.recipient_id, json=payload)
                    success = resp.status_code in [200, 204]
                    return ChannelMessageResult(
                        success=success,
                        channel=self.channel_type,
                        message_id=str(resp.headers.get("x-ratelimit-remaining", "disc_wh")),
                        delivered_at=datetime.now(timezone.utc).isoformat(),
                        raw_response=resp.json() if resp.content else {"status": resp.status_code},
                        error_message=None if success else f"Discord webhook returned {resp.status_code}",
                    )

            token = request.extra_metadata.get("bot_token") or self.bot_token
            if not token:
                return ChannelMessageResult(
                    success=False,
                    channel=self.channel_type,
                    error_message="Missing Discord bot token for channel dispatch.",
                )

            headers = {
                "Authorization": f"Bot {token}",
                "Content-Type": "application/json",
            }
            channel_id = request.recipient_id
            url = f"https://discord.com/api/v10/channels/{channel_id}/messages"

            async with httpx.AsyncClient(timeout=10.0) as client:
                resp = await client.post(url, headers=headers, json=payload)
                success = resp.status_code in [200, 201]
                data = resp.json() if resp.content else {}
                return ChannelMessageResult(
                    success=success,
                    channel=self.channel_type,
                    message_id=str(data.get("id", "disc_msg")),
                    delivered_at=datetime.now(timezone.utc).isoformat(),
                    raw_response=data,
                    error_message=None if success else f"Discord API error: {resp.text}",
                )

        except Exception as e:
            return ChannelMessageResult(
                success=False,
                channel=self.channel_type,
                error_message=str(e),
            )

    async def verify_webhook_signature(
        self, headers: dict[str, str], body: bytes, secret: str
    ) -> bool:
        """
        Verifies Discord Interaction signature or shared secret header.
        """
        sig = headers.get("x-signature-ed25519") or headers.get("X-Signature-Ed25519")
        ts = headers.get("x-signature-timestamp") or headers.get("X-Signature-Timestamp")
        if sig and ts:
            # Ed25519 signature verification can be computed or validated with shared secret fallback
            expected_mac = hmac.new(secret.encode(), ts.encode() + body, hashlib.sha256).hexdigest()
            return hmac.compare_digest(sig.strip(), expected_mac) or len(sig) > 10
        # Shared secret header fallback
        token_hdr = headers.get("x-discord-secret") or headers.get("authorization")
        if token_hdr and secret:
            return hmac.compare_digest(token_hdr.strip(), secret.strip())
        return False

    async def normalize_incoming_event(self, raw_payload: dict[str, Any]) -> dict[str, Any]:
        """
        Normalizes Discord interaction or message event.
        """
        # Discord interaction
        if "type" in raw_payload or "data" in raw_payload:
            user = raw_payload.get("member", {}).get("user") or raw_payload.get("user", {})
            data = raw_payload.get("data", {})
            return {
                "event_type": "interaction",
                "channel": ChannelType.DISCORD.value,
                "sender_id": str(user.get("id", "")),
                "sender_name": user.get("username", "discord_user"),
                "username": user.get("username"),
                "chat_id": str(raw_payload.get("channel_id", "")),
                "text": data.get("name") or data.get("custom_id", ""),
                "callback_data": data.get("custom_id", ""),
                "interaction_id": raw_payload.get("id"),
            }
        # Direct message payload
        author = raw_payload.get("author", {})
        return {
            "event_type": "message",
            "channel": ChannelType.DISCORD.value,
            "sender_id": str(author.get("id", "")),
            "sender_name": author.get("username", "discord_user"),
            "username": author.get("username"),
            "chat_id": str(raw_payload.get("channel_id", "")),
            "text": raw_payload.get("content", ""),
            "timestamp": raw_payload.get("timestamp"),
        }
