"""
Microsoft Teams (Graph API) client.
"""

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

from ..._shared.auth import AuthProvider, AutoAuth, FabricAuth, ServicePrincipalAuth
from ..._shared.client import BaseClient
from ..._shared.runtime import runtime
from .channel import Channel


class TeamsClient(BaseClient):
    """
    HTTP client for Microsoft Teams via Graph API.

    Configured for a specific team with a default channel.
    """

    GRAPH_SCOPE = "https://graph.microsoft.com/.default"
    GRAPH_API_URL = "https://graph.microsoft.com/v1.0"

    def __init__(
        self,
        team_id: str,
        channel_id: str,
        auth: Optional[AuthProvider] = None,
        tenant_id: Optional[str] = None,
        client_id: Optional[str] = None,
        client_secret: Optional[str] = None,
    ):
        """
        Initialize the Teams client.

        Args:
            team_id: Microsoft Teams team ID
            channel_id: Default channel ID
            auth: Optional pre-configured AuthProvider
            tenant_id: Azure AD tenant ID
            client_id: Application client ID
            client_secret: Client secret
        """
        # Determine authentication method
        if auth:
            auth_provider = auth
        elif tenant_id and client_id and client_secret:
            auth_provider = ServicePrincipalAuth(
                tenant_id=tenant_id, client_id=client_id, client_secret=client_secret
            )
        elif runtime.isFabric:
            auth_provider = FabricAuth()
        else:
            auth_provider = AutoAuth(
                tenant_id=tenant_id, client_id=client_id, client_secret=client_secret
            )

        super().__init__(auth_provider)

        self._team_id = team_id
        self._channel_id = channel_id
        self._scope = self.GRAPH_SCOPE
        self._base_uri = self.GRAPH_API_URL

    @property
    def teamId(self) -> str:
        """Get the configured team ID."""
        return self._team_id

    @property
    def channelId(self) -> str:
        """Get the default channel ID."""
        return self._channel_id

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

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

        Returns:
            dict: API response
        """
        return self.channel(self._channel_id).send(content, subject)

    def channel(self, channel_id: str) -> Channel:
        """
        Get a Channel object for a specific channel.

        Args:
            channel_id: Channel ID

        Returns:
            Channel: Channel for sending messages
        """
        return Channel(self, self._team_id, channel_id)

    def listChannels(self) -> List[Dict[str, Any]]:
        """
        List all channels in the team.

        Returns:
            list: List of channel metadata
        """
        response = self.get(f"/teams/{self._team_id}/channels")
        return response.json().get("value", [])

    def getResource(self, resource_type: str, **kwargs) -> Any:
        """
        Generic resource access for dynamic __getattr__ fallback.

        Args:
            resource_type: Resource type/path

        Returns:
            API response data
        """
        endpoint = f"/teams/{self._team_id}/{resource_type}"
        response = self.get(endpoint)
        data = response.json()

        if "value" in data:
            return data["value"]
        return data
