"""News ticker for admin monitor.

Fetches news from RSS feeds relevant to AI agents and security.
Zero external dependencies - uses stdlib only.
"""
import json
import urllib.request
import urllib.error
import xml.etree.ElementTree as ET
from html import unescape
from datetime import datetime


# RSS feeds - AI agents, security, trust, infrastructure
RSS_FEEDS = [
    # AI Labs
    ("Anthropic", "https://www.anthropic.com/feed"),
    ("OpenAI", "https://openai.com/blog/rss/"),
    ("DeepMind", "https://deepmind.google/blog/rss.xml"),
    ("Google AI", "https://blog.google/technology/ai/rss/"),

    # AI Engineering / Agents
    ("LangChain", "https://blog.langchain.dev/rss/"),
    ("Hugging Face", "https://huggingface.co/blog/feed.xml"),

    # Security
    ("Krebs on Security", "https://krebsonsecurity.com/feed/"),
    ("Schneier", "https://www.schneier.com/feed/atom/"),
    ("The Hacker News", "https://feeds.feedburner.com/TheHackersNews"),

    # Tech/Startup
    ("Hacker News", "https://hnrss.org/frontpage?count=5"),
    ("TechCrunch AI", "https://techcrunch.com/tag/artificial-intelligence/feed/"),
]

TIMEOUT = 3  # Fast timeout - news is non-critical


def _fetch_rss(name: str, url: str) -> list[tuple[str, str]]:
    """Fetch headlines from RSS feed. Returns [(source, title), ...]."""
    try:
        req = urllib.request.Request(
            url,
            headers={"User-Agent": "obol-sdk/0.1.0"},
        )
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            content = resp.read().decode()

        root = ET.fromstring(content)
        headlines = []

        # Try Atom format first
        ns = {"atom": "http://www.w3.org/2005/Atom"}
        entries = root.findall(".//atom:entry/atom:title", ns)
        if entries:
            for e in entries[:3]:
                if e.text:
                    headlines.append((name, unescape(e.text.strip())))
            return headlines

        # Try RSS format
        items = root.findall(".//item/title")
        if items:
            for i in items[:3]:
                if i.text:
                    headlines.append((name, unescape(i.text.strip())))
            return headlines

        return []
    except Exception:
        return []


def fetch_news_headlines() -> list[tuple[str, str]]:
    """Fetch headlines from all RSS feeds.

    Returns: [(source, title), ...] - max 15 headlines, 2 per feed
    """
    import concurrent.futures

    all_headlines = []

    # Parallel fetch for speed (news panel shouldn't block UI)
    with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
        futures = {
            executor.submit(_fetch_rss, name, url): name
            for name, url in RSS_FEEDS
        }

        for future in concurrent.futures.as_completed(futures, timeout=5):
            try:
                headlines = future.result()
                all_headlines.extend(headlines[:2])  # Max 2 per source
            except Exception:
                pass  # Feed failed, skip it

    # Deduplicate by title (case-insensitive)
    seen = set()
    unique = []
    for source, title in all_headlines:
        title_lower = title.lower()
        if title_lower not in seen and len(title) > 10:  # Skip very short titles
            seen.add(title_lower)
            unique.append((source, title))

    return unique[:15]


def format_headline(source: str, title: str, max_width: int = 100) -> str:
    """Format a headline for display with source prefix."""
    # Truncate long titles
    prefix = f"[{source}] "
    available = max_width - len(prefix) - 3
    if len(title) > available:
        title = title[:available] + "..."
    return f"{prefix}{title}"


if __name__ == "__main__":
    # Quick test
    print("Fetching news from RSS feeds...\n")
    headlines = fetch_news_headlines()
    if not headlines:
        print("No headlines fetched (network issue?)")
    else:
        print(f"Got {len(headlines)} headlines:\n")
        for source, title in headlines:
            print(format_headline(source, title))
