"""Hacker News — Firebase API."""

from __future__ import annotations

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


def fetch_hacker_news(cfg: dict, fetcher: Fetcher) -> list[Item]:
    base = cfg.get("endpoint", "https://hacker-news.firebaseio.com/v0")
    top_n = cfg.get("fetch_top_n", 60)
    min_score = cfg.get("min_score", 80)
    max_items = cfg.get("max_items", 20)

    print("Fetching Hacker News...")
    resp = fetcher.get(f"{base}/topstories.json")
    if not resp:
        return []

    story_ids = resp.json()[:top_n]
    items = []
    for sid in story_ids:
        if len(items) >= max_items * 2:
            break
        r = fetcher.get(f"{base}/item/{sid}.json")
        if not r:
            continue
        s = r.json()
        if not s or s.get("type") != "story":
            continue
        if s.get("score", 0) < min_score:
            continue
        url = s.get("url") or f"https://news.ycombinator.com/item?id={sid}"
        items.append(Item(
            title=s.get("title", ""),
            url=url,
            source="Hacker News",
            summary="",
            engagement={
                "upvotes": s.get("score", 0),
                "comments": s.get("descendants", 0),
            },
        ))

    print(f"  -> {len(items)} items above score threshold")
    return items[:max_items]
