"""arXiv — RSS feeds."""

from __future__ import annotations

import re
from xml.etree import ElementTree as ET

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


def fetch_arxiv(cfg: dict, fetcher: Fetcher) -> list[Item]:
    max_per = cfg.get("max_items_per_feed", 10)
    items = []

    for feed in cfg.get("feeds", []):
        url = feed["url"]
        label = feed.get("label", "arXiv")
        print(f"Fetching arXiv [{label}]...")
        resp = fetcher.get(url)
        if not resp:
            continue
        try:
            root = ET.fromstring(resp.text)
        except ET.ParseError as e:
            print(f"  [parse error] {e}")
            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 or link_el is None:
                continue
            title = (title_el.text or "").strip()
            link = (link_el.text or "").strip()
            if not link:
                link = entry.findtext("guid", "")
            desc = (desc_el.text or "") if desc_el is not None else ""
            desc = re.sub(r"<[^>]+>", "", desc).strip()

            items.append(Item(
                title=title,
                url=link,
                source=f"arXiv / {label}",
                summary=desc[:400],
                tags=[label],
            ))
            count += 1

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

    return items
