"""Flipboard — topic RSS feeds. 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://flipboard.com/topic"


def fetch_flipboard(cfg: dict, fetcher: Fetcher) -> list[Item]:
    """Fetch Flipboard topic RSS feeds."""
    max_per = cfg.get("max_items_per_topic", 5)
    topics = cfg.get("topics", [])
    items = []

    for topic in topics:
        url = f"{_BASE}/{topic}.rss"
        print(f"Fetching Flipboard [{topic}]...")
        resp = fetcher.get(url)
        if not resp:
            continue

        try:
            root = ET.fromstring(resp.text)
        except ET.ParseError:
            continue

        channel = root.find("channel")
        if channel is None:
            continue

        count = 0
        for entry in channel.findall("item"):
            if count >= max_per:
                break
            title_el = entry.find("title")
            link_el = entry.find("link")
            desc_el = entry.find("description")
            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()

            # Try to extract image from description HTML
            image_url = ""
            if desc_el is not None and desc_el.text:
                img_match = re.search(r'<img[^>]+src=["\']([^"\']+)["\']', desc_el.text)
                if img_match:
                    image_url = img_match.group(1)

            items.append(Item(
                title=title,
                url=link,
                source="Flipboard",
                summary=desc[:400],
                image_url=image_url,
                tags=[topic.title()],
            ))
            count += 1

        print(f"  -> {count} items")

    return items
