#!/usr/bin/env python3
"""Fetch hot posts from all subreddits via JSON API, output pipe-delimited lines."""
import json
import urllib.request
import urllib.error
import sys
import time

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",
    "Accept": "application/json",
}

def fetch_sub(sub):
    url = f"https://www.reddit.com/r/{sub}/hot.json?limit=5"
    req = urllib.request.Request(url, headers=HEADERS)
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            data = json.loads(resp.read().decode())
    except Exception as e:
        return None, str(e)
    
    posts = []
    for child in data.get("data", {}).get("children", []):
        d = child.get("data", {})
        if d.get("stickied"):
            continue
        title = d.get("title", "").replace("\n", " ").replace("|", "/")
        ups = d.get("ups", 0)
        url_short = d.get("url", "")
        posts.append((title, ups, url_short))
        if len(posts) >= 3:
            break
    return posts, None

all_results = {}
for cat, sub_list in SUBS.items():
    cat_posts = []
    for sub in sub_list:
        posts, err = fetch_sub(sub)
        time.sleep(0.3)  # rate limit courtesy
        if posts and len(posts) > 0:
            for t, u, url in posts:
                cat_posts.append((sub, t, u, url))
        elif err:
            cat_posts.append((sub, f"[ERROR: {err}]", 0, ""))
        else:
            cat_posts.append((sub, "[geen niet-stickied posts]", 0, ""))
    # Sort by upvotes desc
    cat_posts.sort(key=lambda x: x[2], reverse=True)
    # Keep top 3 across the category
    all_results[cat] = cat_posts[:5]

# Output: pipe-delimited
for cat, posts in all_results.items():
    has_content = any(p[1] and "[geen" not in p[1] and "[ERROR" not in p[1] for p in posts)
    if not has_content:
        print(f"CATEGORY|{cat}|NONE||")
    else:
        for sub, title, ups, url in posts:
            if "[geen" in title or "[ERROR" in title:
                continue
            print(f"CATEGORY|{cat}|{sub}|{title}|{ups}|{url}")
