"""Default LLM-based message analyzer for the channel monitor.

The analyzer is decoupled from the monitor — it's a callable:
    async (channel, messages, topics) -> list[MonitorAlert]

Users can replace it with any function matching this signature.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any, Awaitable, Callable

from ._types import BatchAnalysis, MonitorAlert

if TYPE_CHECKING:
    pass

logger = logging.getLogger(__name__)

AnalyzerFn = Callable[[str, list[dict], list[str]], Awaitable[list[MonitorAlert]]]

DEFAULT_PROMPT = """Analyze these Telegram channel messages from {channel}.

Monitored topics:
{topics}

For each message, determine:
1. Does it match ANY monitored topic? (is_alert=true/false)
2. Which topic matched? (empty string if none)
3. Urgency: "high" for breaking/urgent, "medium" for important, "low" for informational
4. Brief summary in Russian (1-2 sentences)

Only set is_alert=true if the message is genuinely relevant to a monitored topic.
Ads, spam, and off-topic messages should be is_alert=false.

Messages:
{messages}"""


def create_llm_analyzer(
    sdk: Any,
    model: str,
    prompt_template: str | None = None,
) -> AnalyzerFn:
    """Create an analyzer backed by sdk.parse() with structured output.

    Args:
        sdk: AsyncSDKRouter instance (used for sdk.parse()).
        model: LLM model ID for analysis.
        prompt_template: Custom prompt with {channel}, {topics}, {messages} placeholders.

    Returns:
        Async callable matching AnalyzerFn signature.
    """
    template = prompt_template or DEFAULT_PROMPT

    async def analyze(
        channel: str, messages: list[dict], topics: list[str],
    ) -> list[MonitorAlert]:
        topics_str = "\n".join(f"  - {t}" for t in topics)
        msgs_str = "\n\n".join(
            f"[msg_id={m['message_id']}] ({m.get('date', '')}) "
            f"{m.get('text', '(no text)')[:600]}"
            for m in messages
        )

        prompt = template.format(
            channel=channel, topics=topics_str, messages=msgs_str,
        )

        try:
            result = await sdk.parse(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                response_format=BatchAnalysis,
                temperature=0.1,
            )
            parsed = result.choices[0].message.parsed
            if not parsed:
                return []
        except Exception as e:
            logger.error("LLM analysis failed for %s: %s", channel, e)
            return []

        # Build message lookup for enrichment
        msg_by_id = {m["message_id"]: m for m in messages}

        alerts = []
        for a in parsed.results:
            if not a.is_alert:
                continue
            msg = msg_by_id.get(a.message_id)
            alerts.append(MonitorAlert(
                message_id=a.message_id,
                channel=channel,
                topic=a.topic,
                urgency=a.urgency,
                summary=a.summary,
                original_text=(msg.get("text", "") if msg else "")[:500],
                timestamp=msg.get("date", "") if msg else "",
                sender_id=msg.get("sender_id") if msg else None,
            ))

        return alerts

    return analyze
