from __future__ import annotations

from .configuration import Configuration
from .connection import Connection
from .errors import AuthenticationError
from .resources.sessions import Sessions
from .resources.messages import Messages
from .resources.webhooks import Webhooks
from .resources.usage import Usage
from .resources.business_accounts import BusinessAccounts
from .resources.connects import Connects
from .resources.business_messages import BusinessMessages
from .resources.templates import Templates
from .resources.agents import Agents
from .resources.agent_runs import AgentRuns


class WhatsrbCloud:
    def __init__(
        self,
        api_key: str | None = None,
        *,
        base_url: str | None = None,
        timeout: int | None = None,
    ):
        import whatsrb_cloud as _pkg
        config = _pkg._global_configuration

        self._api_key = api_key or config.api_key
        if not self._api_key:
            raise AuthenticationError("API key is required")

        self._base_url = base_url or config.base_url
        self._timeout = timeout or config.timeout
        self._connection = Connection(
            api_key=self._api_key,
            base_url=self._base_url,
            timeout=self._timeout,
        )

    def __repr__(self) -> str:
        return f"<WhatsrbCloud base_url={self._base_url!r} api_key=[FILTERED]>"

    @property
    def sessions(self) -> Sessions:
        return Sessions(client=self, connection=self._connection)

    def messages(self, session_id: str) -> Messages:
        return Messages(connection=self._connection, session_id=session_id)

    @property
    def webhooks(self) -> Webhooks:
        return Webhooks(connection=self._connection)

    @property
    def usage(self) -> dict:
        return Usage(connection=self._connection).fetch()

    @property
    def business_accounts(self) -> BusinessAccounts:
        return BusinessAccounts(client=self, connection=self._connection)

    @property
    def connects(self) -> Connects:
        return Connects(client=self, connection=self._connection)

    def business_messages(self, account_id: str) -> BusinessMessages:
        return BusinessMessages(connection=self._connection, account_id=account_id)

    def templates(self, account_id: str) -> Templates:
        return Templates(connection=self._connection, account_id=account_id)

    @property
    def agents(self) -> Agents:
        return Agents(client=self, connection=self._connection)

    def agent_runs(self, agent_id: str) -> AgentRuns:
        return AgentRuns(client=self, connection=self._connection, agent_id=agent_id)
