"""GitHub-Trending-Helper — HTML-Scrape (defensiv)."""
from __future__ import annotations

import datetime as dt
import html
import logging
import re
import urllib.request

log = logging.getLogger(__name__)

TRENDING_URL = "https://github.com/trending?since=daily&spoken_language_code=en"
USER_AGENT = "aria-radar/0.1 (+aseckzai@gmail.com)"
TIMEOUT_SECONDS = 20

REPO_BLOCK_RE = re.compile(
    r'<h2[^>]*class="h3 lh-condensed"[^>]*>\s*<a[^>]*?\bhref="(?P<path>/[^"]+/[^"]+?)"[^>]*>.*?</h2>'
    r'(?P<after>.*?)(?=<article|</main>|$)',
    re.IGNORECASE | re.DOTALL,
)
DESCRIPTION_RE = re.compile(
    r'<p[^>]*color-fg-muted[^>]*>(?P<desc>.*?)</p>',
    re.IGNORECASE | re.DOTALL,
)
STARS_TODAY_RE = re.compile(r'([\d,]+)\s*stars\s*today', re.IGNORECASE)
LANGUAGE_RE = re.compile(r'itemprop="programmingLanguage">([^<]+)<')


def fetch(*, since: dt.datetime, max_items: int = 25) -> list[dict]:
    """Scrape trending repos from GitHub. Defensive."""
    req = urllib.request.Request(TRENDING_URL, headers={"User-Agent": USER_AGENT, "Accept": "text/html"})
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
            body = resp.read().decode("utf-8", errors="replace")
    except Exception as exc:  # noqa: BLE001
        log.warning("github_trending fetch failed: %s", exc)
        return []

    blocks = list(REPO_BLOCK_RE.finditer(body))
    if not blocks:
        log.warning("github_trending: no repo blocks parsed — HTML layout may have changed")
        return []

    now_iso = dt.datetime.now(dt.timezone.utc).isoformat()
    items: list[dict] = []
    for block in blocks[:max_items]:
        path = re.sub(r"\s+", "", block.group("path"))
        if not path.startswith("/") or path.count("/") < 2:
            continue
        after = block.group("after")
        desc_match = DESCRIPTION_RE.search(after)
        description = None
        if desc_match:
            description = html.unescape(re.sub(r"\s+", " ", desc_match.group("desc")).strip())
        stars_match = STARS_TODAY_RE.search(after)
        stars_today = int(stars_match.group(1).replace(",", "")) if stars_match else None
        lang_match = LANGUAGE_RE.search(after)
        language = lang_match.group(1) if lang_match else None

        items.append({
            "title": path.lstrip("/"),
            "url": f"https://github.com{path}",
            "date": now_iso,
            "source": "github_trending",
            "score": stars_today,
            "raw": {
                "description": description,
                "language": language,
            },
        })
    log.info("github_trending: %d items", len(items))
    return items


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