"""
Microsoft Teams Channel model.
"""

from typing import TYPE_CHECKING, Any, Dict, Optional, Union

from ..._shared.utils import GUID

if TYPE_CHECKING:
    from .client import TeamsClient


class Channel:
    """
    Represents a Microsoft Teams channel.

    Provides methods to send messages, including Adaptive Cards.

    Examples:
        >>> import fabias.teams as teams
        >>> teams.client(team_id="...", channel_id="...", auth=auth)
        >>> teams.send("Hello!")  # Default channel
        >>> teams.channel("other-id").send("Hello other channel!")
    """

    def __init__(self, client: "TeamsClient", team_id: str, channel_id: str):
        """
        Initialize channel.

        Args:
            client: Configured TeamsClient
            team_id: Parent team ID
            channel_id: Channel ID
        """
        self._client = client
        self.teamId = team_id
        self.id = channel_id

    def send(self, content: Union[str, Any], subject: Optional[str] = None) -> dict:
        """
        Send a message to this channel.

        Args:
            content: Message text or Adaptive Card
            subject: Optional message subject

        Returns:
            dict: API response with message ID

        Examples:
            >>> channel.send("Hello world!")
            >>> channel.send("Alert message", subject="Important")
            >>> channel.send(my_adaptive_card)
        """
        endpoint = f"/teams/{self.teamId}/channels/{self.id}/messages"

        # Build message body
        body: Dict[str, Any] = {
            "subject": subject,
            "body": {"contentType": "html", "content": content if isinstance(content, str) else ""},
        }

        # Check for Adaptive Card
        try:
            from ..cards import Adaptive

            if isinstance(content, Adaptive):
                attachment_id = GUID.hex()
                body_content: Dict[str, str] = body["body"]  # Type annotation for nested dict
                body_content["content"] = f'<attachment id="{attachment_id}"></attachment>'
                body["attachments"] = [
                    {
                        "id": attachment_id,
                        "contentType": "application/vnd.microsoft.card.adaptive",
                        "contentUrl": None,
                        "content": content.content(),
                        "name": None,
                        "thumbnailUrl": None,
                    }
                ]
        except ImportError:
            pass

        response = self._client.post(endpoint, data=body)
        return response.json()

    def __repr__(self) -> str:
        return f"Channel(id={self.id}, teamId={self.teamId})"
