"""Resumidor SIMPLE (extractivo): sin IA, sin coste.

Agrupa los tweets TOP, detecta los temas más frecuentes y arma un digest legible.
Más adelante añadiremos un ClaudeSummarizer con la misma interfaz para resúmenes
redactados de verdad.
"""

import re
from collections import Counter
from typing import List, Optional, Tuple

from agent.models import Tweet
from agent.summarizers.base import Summarizer


def _excerpt(text: str, limit: int = 220) -> str:
    text = " ".join(text.split())
    return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"


class SimpleSummarizer(Summarizer):
    def summarize(self, ranked: List[Tuple[float, Tweet]], topics: Optional[List[str]] = None) -> str:
        if not ranked:
            return "_No hay tweets en la ventana de tiempo seleccionada._"

        authors = Counter(t.author for _, t in ranked)
        total_eng = sum(t.engagement for _, t in ranked)

        # Temas detectados: cuáles de tus 'topics' aparecen más.
        theme_hits = Counter()
        if topics:
            joined = " ".join(t.text.lower() for _, t in ranked)
            for topic in topics:
                hits = len(re.findall(re.escape(topic.lower()), joined))
                if hits:
                    theme_hits[topic] = hits

        lines: List[str] = []
        lines.append(f"### 🔝 Resumen TOP — {len(ranked)} tweets destacados")
        lines.append("")
        lines.append(
            f"**Cuentas más presentes:** "
            + ", ".join(f"@{a} ({n})" for a, n in authors.most_common(5))
        )
        if theme_hits:
            lines.append(
                f"**Temas calientes:** "
                + ", ".join(f"{t} ({n})" for t, n in theme_hits.most_common(6))
            )
        lines.append(f"**Engagement total del TOP:** {total_eng:,} interacciones")
        lines.append("")
        lines.append("---")
        lines.append("")

        for i, (score, t) in enumerate(ranked, 1):
            lines.append(
                f"**{i}. @{t.author}** · ❤️ {t.likes:,} · 🔁 {t.retweets:,} · "
                f"💬 {t.replies:,} · _score {score}_"
            )
            lines.append("")
            lines.append(f"> {_excerpt(t.text)}")
            lines.append("")
            lines.append(f"[Abrir tweet →]({t.url})")
            lines.append("")

        return "\n".join(lines)
