"""Telegram channel monitor — polls channels, analyzes via LLM, sends alerts.

Usage:
    from sdkrouter import AsyncSDKRouter

    sdk = AsyncSDKRouter(api_key="sk_live_...")

    # As bot — notify a group chat
    monitor = sdk.telegram.monitor(
        channels=["@forklogAI"],
        topics=["new token listing"],
        chat_ids=[-796503018],
    )
    await monitor.run()

    # As async iterator
    async for alert in sdk.telegram.monitor(channels=[...], topics=[...]):
        print(alert.summary)
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ._analyzer import AnalyzerFn, create_llm_analyzer
from ._config import MonitorConfig
from ._monitor import ChannelMonitor
from ._notifier import Notifier
from ._types import BatchAnalysis, MessageAnalysis, MonitorAlert

if TYPE_CHECKING:
    import httpx


class AsyncMonitorMixin:
    """Mixin adding monitor() to AsyncTelegramResource. Async-only."""

    _tg_client: httpx.AsyncClient
    _parent: Any  # AsyncSDKRouter back-reference set by LazyTool

    def monitor(
        self,
        channels: list[str],
        topics: list[str],
        *,
        account: str = "main",
        chat_ids: list[int | str] | None = None,
        bot: str = "",
        model: str = "deepseek/deepseek-chat-v3-0324",
        interval: float = 10.0,
        batch_size: int = 50,
        max_concurrent_llm: int = 5,
        min_text_length: int = 10,
        max_text_length: int = 2000,
        prompt_template: str | None = None,
        analyzer: AnalyzerFn | None = None,
    ) -> ChannelMonitor:
        """Create a channel monitor that polls, analyzes, and yields alerts.

        Args:
            channels: Channels to monitor (e.g. ["@forklogAI"]).
            topics: Topics for LLM analysis (e.g. ["new token listing"]).
            account: MTProto account alias.
            chat_ids: Chat IDs to send alerts to (group chats, users).
                Sent via MTProto (account_send_message) by default,
                or via bot if ``bot`` is also provided.
            bot: Bot alias for sending alerts. If empty, uses MTProto.
            model: LLM model for analysis.
            interval: Seconds between poll cycles.
            analyzer: Custom analyzer function. If None, uses LLM.

        Returns:
            ChannelMonitor — use ``await monitor.run()`` or ``async for alert in monitor``.

        Example:
            monitor = sdk.telegram.monitor(
                channels=["@forklogAI"],
                topics=["new listing"],
                chat_ids=[-796503018],
            )
            await monitor.run()
        """
        config = MonitorConfig(
            account=account,
            channels=channels,
            topics=topics,
            bot=bot,
            admin_ids=chat_ids or [],
            model=model,
            interval=interval,
            batch_size=batch_size,
            max_concurrent_llm=max_concurrent_llm,
            min_text_length=min_text_length,
            max_text_length=max_text_length,
            prompt_template=prompt_template,
        )

        if analyzer is None:
            analyzer = create_llm_analyzer(self._parent, model, prompt_template)

        notifier = None
        if chat_ids:
            if bot:
                notifier = Notifier(
                    self.send_message, chat_ids,  # type: ignore[attr-defined]
                    mode="bot", bot=bot,
                )
            else:
                notifier = Notifier(
                    self.account_send_message, chat_ids,  # type: ignore[attr-defined]
                    mode="mtproto", account=account,
                )

        return ChannelMonitor(
            config=config,
            poll_fn=self.account_poll_messages,  # type: ignore[attr-defined]
            analyzer=analyzer,
            notifier=notifier,
        )


__all__ = [
    "AsyncMonitorMixin",
    "ChannelMonitor",
    "MonitorConfig",
    "MonitorAlert",
    "MessageAnalysis",
    "BatchAnalysis",
    "AnalyzerFn",
]
