#!/usr/bin/env python3
"""Fallback: fetch Reddit via RSS (old.reddit.com .rss)."""
import xml.etree.ElementTree as ET
import urllib.request
import urllib.error
import time
import json

SUBS = {
    "Luchtvaart & radio": ["ADSBexchange","ADSB","flightradar24","aviation","airplanes","Gliding","Baofeng","RTLSDR","meshtastic"],
    "Cybersecurity & OSINT": ["cybersecurity","OSINT","bellingcat","Kalilinux","tryhackme","flipperzero","lockpicking","wardrivers","Adguard"],
    "AI & modellen": ["OpenAI","ClaudeAI","DeepSeek"],
    "Wearables, sport & gezondheid": ["Garmin","Garmininstinct","GarminEdge","GarminTactix","fitbit","Strava","Zwift","running","peloton","Biohackers"],
    "Outdoor, bikepacking & reizen": ["bikepacking","Ultralight","CamperVans","VanlifeEurope","orienteering","Meteograms"],
    "Tactisch, defensie & uitrusting": ["TacticalMedicine","511tactical","Military","Glock19"],
    "België, Europa & lokaal": ["Antwerpen","belgium","europe"],
    "Gaming & entertainment": ["GhostRecon","Doom","doorkickers","TombRaider"],
    "Maker, hardware & niche": ["BambuLab","Xennials"]
}

HEADERS = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}

def parse_rss_entry(entry):
    """Extract title, ups estimate from RSS entry."""
    ns = {"atom": "http://www.w3.org/2005/Atom"}
    title_el = entry.find("atom:title", ns)
    title = title_el.text.strip() if title_el is not None and title_el.text else "[geen titel]"
    title = title.replace("\n", " ").replace("|", "/")
    
    # RSS doesn't have upvotes, estimate n/a
    # Try to get link
    link_el = entry.find("atom:link", ns)
    url = link_el.get("href", "") if link_el is not None else ""
    
    return title, url

def fetch_sub_rss(sub):
    """Fetch via old.reddit.com RSS."""
    url = f"https://old.reddit.com/r/{sub}/hot/.rss"
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            body = resp.read().decode()
    except Exception as e:
        return None, str(e)
    
    ns = {"atom": "http://www.w3.org/2005/Atom"}
    root = ET.fromstring(body)
    entries = root.findall("atom:entry", ns)
    
    posts = []
    for entry in entries:
        title, url = parse_rss_entry(entry)
        # Skip stickied: no way to detect from RSS, just keep top 3
        posts.append((title, url))
        if len(posts) >= 3:
            break
    
    if not posts:
        return None, "empty feed"
    return posts, None

all_results = {}
for cat, sub_list in SUBS.items():
    cat_posts = []
    for sub in sub_list:
        posts, err = fetch_sub_rss(sub)
        time.sleep(0.2)
        if posts:
            for title, url in posts:
                cat_posts.append((sub, title, url))
        else:
            pass  # skip failed subs silently
    
    all_results[cat] = cat_posts[:5]

# Output in digest format (pipe-delimited for post-processing)
for cat, posts in all_results.items():
    if not posts:
        print(f"CATEGORY|{cat}|NONE||")
    else:
        for sub, title, url in posts:
            print(f"CATEGORY|{cat}|{sub}|{title}|{url}")
