"""Hacker News Algolia — search API for specific queries."""

from __future__ import annotations

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


def fetch_hn_algolia(cfg: dict, fetcher: Fetcher) -> list[Item]:
    base = cfg.get("endpoint", "https://hn.algolia.com/api/v1")
    queries = cfg.get("queries", [])
    sort = cfg.get("sort", "search_by_date")  # or "search"
    max_items = cfg.get("max_items", 10)
    items = []

    for query in queries:
        print(f"Fetching HN Algolia [{query[:40]}]...")
        endpoint = f"{base}/{sort}"
        params = {
            "query": query,
            "tags": "story",
            "hitsPerPage": max_items,
        }
        resp = fetcher.get(endpoint, params=params)
        if not resp:
            continue
        data = resp.json()
        for hit in data.get("hits", []):
            url = hit.get("url") or f"https://news.ycombinator.com/item?id={hit.get('objectID', '')}"
            items.append(Item(
                title=hit.get("title", ""),
                url=url,
                source="HN Algolia",
                summary="",
                engagement={
                    "upvotes": hit.get("points", 0),
                    "comments": hit.get("num_comments", 0),
                },
            ))

    print(f"  -> {len(items)} total items")
    return items
