"""GitHub-Helper — REST Search API, Tier-1-Topics, PAT-auth."""
from __future__ import annotations

import datetime as dt
import json
import logging
import os
import time
import urllib.parse
import urllib.request

log = logging.getLogger(__name__)

API_BASE = "https://api.github.com"
USER_AGENT = "aria-radar/0.1 (+aseckzai@gmail.com)"
TIMEOUT_SECONDS = 20

TIER_1_TOPICS = [
    "claude-code",
    "mcp-server",
    "model-context-protocol",
    "llm-agents",
    "ai-agents",
    "agent-framework",
    "prompt-injection",
    "llm-security",
    "claude",
    "anthropic",
]


def _search_topic(topic: str, since_date: str, token: str, max_items: int) -> list[dict]:
    query = f"topic:{topic} pushed:>{since_date}"
    params = {"q": query, "sort": "stars", "order": "desc", "per_page": str(max_items)}
    url = f"{API_BASE}/search/repositories?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(url, headers={
        "User-Agent": USER_AGENT,
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "X-GitHub-Api-Version": "2022-11-28",
    })
    with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
        payload = json.loads(resp.read())

    items: list[dict] = []
    for repo in payload.get("items", []):
        items.append({
            "title": repo.get("full_name", "(unknown)"),
            "url": repo.get("html_url"),
            "date": repo.get("pushed_at"),
            "source": "github",
            "score": repo.get("stargazers_count"),
            "raw": {
                "topic": topic,
                "description": repo.get("description"),
                "language": repo.get("language"),
                "forks": repo.get("forks_count"),
                "open_issues": repo.get("open_issues_count"),
                "license": (repo.get("license") or {}).get("spdx_id"),
            },
        })
    return items


def fetch(*, since: dt.datetime, max_per_topic: int = 5) -> list[dict]:
    """Search GitHub for repos in Tier-1-Topics, pushed after `since`."""
    token = os.environ.get("GITHUB_PERSONAL_ACCESS_TOKEN")
    if not token:
        log.warning("GITHUB_PERSONAL_ACCESS_TOKEN missing — skipping github platform")
        return []

    since_date = since.strftime("%Y-%m-%d")
    all_items: list[dict] = []
    seen_urls: set[str] = set()
    for topic in TIER_1_TOPICS:
        try:
            items = _search_topic(topic, since_date, token, max_per_topic)
        except Exception as exc:  # noqa: BLE001
            log.warning("github topic %s failed: %s", topic, exc)
            continue
        for item in items:
            if item["url"] in seen_urls:
                continue
            seen_urls.add(item["url"])
            all_items.append(item)
        time.sleep(0.5)  # rate-limit politeness; 5000/h auth = ample headroom
    log.info("github: %d unique items from %d topics", len(all_items), len(TIER_1_TOPICS))
    return all_items


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    items = fetch(since=dt.datetime.now(dt.timezone.utc) - dt.timedelta(hours=24))
    print(json.dumps(items, indent=2))
