"""Discord channel implementation using Bot API via webhooks."""

from __future__ import annotations

import logging
from collections.abc import Callable

import httpx

from agntspace.channels.base import Channel, ChannelMessage

log = logging.getLogger(__name__)


class DiscordChannel(Channel):
    """Discord bot channel using interaction webhooks."""

    name = "discord"

    def __init__(self, bot_token: str, webhook_url: str = "") -> None:
        self._token = bot_token
        self._webhook_url = webhook_url
        self._base_url = "https://discord.com/api/v10"
        self._connected = False
        self._message_callback: Callable | None = None
        self._chat_id: str | None = None

    async def connect(self) -> None:
        async with httpx.AsyncClient() as client:
            resp = await client.get(
                f"{self._base_url}/users/@me",
                headers={"Authorization": f"Bot {self._token}"},
            )
            data = resp.json()
            if "id" not in data:
                raise ConnectionError(f"Discord bot token invalid: {data}")
            log.info("Discord connected: %s#%s", data.get("username"), data.get("discriminator"))
        self._connected = True

    async def disconnect(self) -> None:
        self._connected = False
        log.info("Discord disconnected")

    async def send_message(self, chat_id: str, text: str) -> None:
        async with httpx.AsyncClient() as client:
            await client.post(
                f"{self._base_url}/channels/{chat_id}/messages",
                headers={"Authorization": f"Bot {self._token}"},
                json={"content": text},
            )

    async def send_notification(self, chat_id: str, text: str) -> None:
        await self.send_message(chat_id, f"**Notification:** {text}")

    @property
    def is_connected(self) -> bool:
        return self._connected

    async def handle_webhook(self, payload: dict) -> str | None:
        """Process a Discord interaction/message webhook."""
        # Handle MESSAGE_CREATE events
        if payload.get("t") == "MESSAGE_CREATE":
            data = payload.get("d", {})
            # Ignore bot's own messages
            if data.get("author", {}).get("bot"):
                return None

            text = data.get("content", "")
            channel_id = data.get("channel_id", "")
            author = data.get("author", {}).get("username", "User")

            if not text or not channel_id:
                return None

            self._chat_id = channel_id

            msg = ChannelMessage(
                channel="discord",
                sender=author,
                text=text,
                metadata={"chat_id": channel_id},
            )

            if self._message_callback:
                response = await self._message_callback(msg)
                if response:
                    await self.send_message(channel_id, response)
                return response

        return None
