"""GitHub repository search source."""

from __future__ import annotations

import sys

import httpx

GITHUB_API = "https://api.github.com"


def search_repos(
    query: str,
    token: str | None = None,
    max_results: int = 10,
) -> list[dict]:
    """Search GitHub for repositories matching the query."""
    headers = {
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    if token:
        headers["Authorization"] = f"Bearer {token}"
    url = f"{GITHUB_API}/search/repositories"
    params = {
        "q": query,
        "sort": "stars",
        "order": "desc",
        "per_page": max_results,
    }
    try:
        resp = httpx.get(url, headers=headers, params=params, timeout=15)
        resp.raise_for_status()
        data = resp.json()
        return [
            {
                "name": r["full_name"],
                "stars": r["stargazers_count"],
                "description": (r.get("description") or "")[:120],
                "url": r["html_url"],
                "updated": r["updated_at"][:10],
                "language": r.get("language") or "—",
            }
            for r in data.get("items", [])[:max_results]
        ]
    except Exception as e:
        print(f"GitHub search failed for '{query}': {e}", file=sys.stderr)
        return []
