"""Hacker News search source via Algolia API."""

from __future__ import annotations

import sys

import httpx

HN_API = "https://hn.algolia.com/api/v1"


def search_discussions(
    query: str,
    max_results: int = 5,
) -> list[dict]:
    """Search Hacker News for discussions matching the query."""
    url = f"{HN_API}/search"
    params = {
        "query": query,
        "tags": "story",
        "hitsPerPage": max_results,
        "numericFilters": "points>5",
    }
    try:
        resp = httpx.get(url, params=params, timeout=15)
        resp.raise_for_status()
        data = resp.json()
        return [
            {
                "title": h["title"],
                "points": h.get("points", 0),
                "comments": h.get("num_comments", 0),
                "url": f"https://news.ycombinator.com/item?id={h['objectID']}",
                "date": h.get("created_at", "")[:10],
            }
            for h in data.get("hits", [])[:max_results]
        ]
    except Exception as e:
        print(f"HN search failed for '{query}': {e}", file=sys.stderr)
        return []
