"""feeds.py — keyless news sources for the spec runner.

No API keys, no paid tiers, no accounts. RSS/Atom plus the public Hacker News
endpoint. Every fetch has a timeout and a failover, so one dead source never
hangs a run.
"""

from __future__ import annotations

import json
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone

UA = "Jarvis/1.0 (personal research assistant; +https://jarvis.llmscape.com/support.html)"
TIMEOUT = 12
ATOM = "{http://www.w3.org/2005/Atom}"

# Keyless. Ordered by signal quality: AI, business, markets first.
DEFAULT_FEEDS = [
    "https://techcrunch.com/feed/",
    "https://feeds.arstechnica.com/arstechnica/technology-lab",
    "https://feeds.bbci.co.uk/news/business/rss.xml",
    "https://www.theverge.com/rss/index.xml",
    "hackernews",
]


def _get(url):
    req = urllib.request.Request(
        url,
        headers={
            "User-Agent": UA,
            "Accept": "application/rss+xml, application/atom+xml, application/xml, application/json, */*",
        },
    )
    with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
        return resp.read()


def _parse_feed(raw):
    """RSS 2.0 or Atom -> [{title, url, published_at}]."""
    out = []
    try:
        root = ET.fromstring(raw)
    except ET.ParseError:
        return out

    for item in root.iter("item"):
        title = (item.findtext("title") or "").strip()
        link = (item.findtext("link") or "").strip()
        pub = (item.findtext("pubDate") or "").strip()
        if title and link:
            out.append({"title": title, "url": link, "published_at": pub})

    for entry in root.iter(ATOM + "entry"):
        title = (entry.findtext(ATOM + "title") or "").strip()
        link_el = entry.find(ATOM + "link")
        link = (link_el.get("href") if link_el is not None else "") or ""
        pub = (entry.findtext(ATOM + "updated") or "").strip()
        if title and link:
            out.append({"title": title, "url": link, "published_at": pub})

    return out


def _fetch_hn(limit):
    ids = json.loads(_get("https://hacker-news.firebaseio.com/v0/topstories.json"))[:limit]
    out = []
    for story_id in ids:
        try:
            item = json.loads(_get(f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json"))
        except Exception:
            continue
        title = (item.get("title") or "").strip()
        if not title:
            continue
        url = item.get("url") or f"https://news.ycombinator.com/item?id={story_id}"
        ts = item.get("time")
        pub = datetime.fromtimestamp(ts, tz=timezone.utc).isoformat() if ts else ""
        out.append({"title": title, "url": url, "published_at": pub})
    return out


def _within_window(published_at, cutoff):
    """Best effort. An unparseable date is kept, not dropped."""
    if not published_at:
        return True
    for fmt in (
        "%a, %d %b %Y %H:%M:%S %z",
        "%a, %d %b %Y %H:%M:%S %Z",
        "%Y-%m-%dT%H:%M:%S%z",
        "%Y-%m-%dT%H:%M:%SZ",
    ):
        try:
            dt = datetime.strptime(published_at, fmt)
        except ValueError:
            continue
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        return dt >= cutoff
    return True


def fetch_articles(feed_ids=None, window_days=7, per_feed=8):
    """Fetch every feed, dedupe by URL, keep what falls inside the window."""
    feeds = [f for f in (feed_ids or DEFAULT_FEEDS) if f]
    try:
        window_days = int(window_days)
    except (TypeError, ValueError):
        window_days = 7
    cutoff = datetime.now(timezone.utc) - timedelta(days=window_days)

    articles, seen = [], set()
    for feed in feeds:
        try:
            if feed in ("hackernews", "hn"):
                batch = _fetch_hn(per_feed)
            else:
                batch = _parse_feed(_get(feed))[:per_feed]
        except Exception:
            continue
        for art in batch:
            url = art.get("url")
            if not url or url in seen:
                continue
            if not _within_window(art.get("published_at"), cutoff):
                continue
            seen.add(url)
            articles.append(art)
    return articles
