"""Reddit — subreddit .json feeds."""

from __future__ import annotations

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


def fetch_reddit(cfg: dict, fetcher: Fetcher) -> list[Item]:
    subreddits = cfg.get("subreddits", ["machinelearning", "science"])
    min_score = cfg.get("min_score", 50)
    max_items = cfg.get("max_items", 15)
    items = []

    for sub in subreddits:
        print(f"Fetching Reddit r/{sub}...")
        resp = fetcher.get(f"https://www.reddit.com/r/{sub}/hot.json?limit=50")
        if not resp:
            continue
        data = resp.json()
        posts = data.get("data", {}).get("children", [])
        count = 0
        for post in posts:
            if count >= max_items:
                break
            d = post.get("data", {})
            if d.get("score", 0) < min_score:
                continue
            if d.get("stickied"):
                continue
            url = d.get("url", "")
            permalink = f"https://reddit.com{d.get('permalink', '')}"
            # Use thumbnail if it's a real URL
            thumb = d.get("thumbnail", "")
            image_url = thumb if thumb.startswith("http") else ""
            # Prefer preview image
            try:
                preview = d["preview"]["images"][0]["source"]["url"]
                image_url = preview.replace("&amp;", "&")
            except (KeyError, IndexError, TypeError):
                pass

            items.append(Item(
                title=d.get("title", ""),
                url=url if url != permalink else permalink,
                source="Reddit",
                summary=d.get("selftext", "")[:400],
                image_url=image_url,
                tags=[f"r/{sub}"],
                engagement={
                    "upvotes": d.get("score", 0),
                    "comments": d.get("num_comments", 0),
                },
            ))
            count += 1

        print(f"  -> {count} items from r/{sub}")

    return items
