"""Google News — RSS feeds by topic and search query. Free, no API key."""

from __future__ import annotations

import re
from xml.etree import ElementTree as ET

from platoon.models import Item
from platoon.fetcher import Fetcher

_BASE = "https://news.google.com/rss"

# Named topics Google News supports directly
_TOPICS = {
    "world", "nation", "business", "technology",
    "entertainment", "science", "sports", "health",
}


def _parse_google_rss(xml_text: str, label: str, max_items: int) -> list[Item]:
    """Parse Google News RSS feed."""
    try:
        root = ET.fromstring(xml_text)
    except ET.ParseError:
        return []

    channel = root.find("channel")
    if channel is None:
        return []

    items = []
    for entry in channel.findall("item")[:max_items]:
        title_el = entry.find("title")
        link_el = entry.find("link")
        desc_el = entry.find("description")
        source_el = entry.find("source")
        if title_el is None:
            continue

        title = (title_el.text or "").strip()
        link = (link_el.text or "").strip()
        desc = ""
        if desc_el is not None and desc_el.text:
            desc = re.sub(r"<[^>]+>", "", desc_el.text).strip()

        # Google News often wraps the real source name in <source>
        pub_source = ""
        if source_el is not None:
            pub_source = (source_el.text or "").strip()

        items.append(Item(
            title=title,
            url=link,
            source=f"Google News",
            summary=desc[:400],
            tags=[label] + ([pub_source] if pub_source else []),
        ))

    return items


def fetch_google_news(cfg: dict, fetcher: Fetcher) -> list[Item]:
    """Fetch Google News by topics and/or search queries."""
    max_per = cfg.get("max_items_per_query", 5)
    lang = cfg.get("lang", "en-US")
    country = cfg.get("country", "US")
    params = f"hl={lang}&gl={country}&ceid={country}:{lang.split('-')[0]}"
    items = []

    # Fetch by named topics
    for topic in cfg.get("topics", []):
        topic_upper = topic.upper()
        if topic_upper not in {t.upper() for t in _TOPICS}:
            continue
        url = f"{_BASE}/headlines/section/topic/{topic_upper}?{params}"
        print(f"Fetching Google News [{topic}]...")
        resp = fetcher.get(url)
        if not resp:
            continue
        parsed = _parse_google_rss(resp.text, topic.title(), max_per)
        print(f"  -> {len(parsed)} items")
        items.extend(parsed)

    # Fetch by search queries
    for query in cfg.get("queries", []):
        from urllib.parse import quote
        url = f"{_BASE}/search?q={quote(query)}&{params}"
        print(f"Fetching Google News [q:{query[:40]}]...")
        resp = fetcher.get(url)
        if not resp:
            continue
        parsed = _parse_google_rss(resp.text, query, max_per)
        print(f"  -> {len(parsed)} items")
        items.extend(parsed)

    return items
