#!/usr/bin/env python3
import os, re, sys, urllib.request, urllib.error

STATUS_FILE = "/tmp/trending_source_status.txt"
HTML_FILE = "/tmp/gh_trending.html"
MIN_REPOS = 8

HEADERS = {"User-Agent": "Mozilla/5.0"}


def fetch_github_trending() -> str:
    req = urllib.request.Request("https://github.com/trending", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=30) as resp:
        return resp.read().decode("utf-8", errors="ignore")


def validate(html: str) -> dict:
    article_count = len(re.findall(r'<article\s+class="Box-row"', html))
    star_matches = re.findall(r'/stargazers"[^>]*>([0-9.,kKmM]+)', html)
    lang_matches = re.findall(r'itemprop="programmingLanguage"[^>]*>([^<]+)', html)
    valid = article_count >= MIN_REPOS and (len(star_matches) > MIN_REPOS // 2 or len(lang_matches) > MIN_REPOS // 2)
    return {
        "article_count": article_count,
        "star_matches": len(star_matches),
        "lang_matches": len(lang_matches),
        "valid": valid,
    }


def main():
    try:
        html = fetch_github_trending()
    except Exception as exc:
        result = {"ok": False, "reason": f"fetch_error: {exc}"}
        with open(STATUS_FILE, "w", encoding="utf-8") as f:
            f.write(f"VALIDATION=0\nREASON=fetch_error\nDETAIL={exc}\n")
        print(f"VALIDATION=0\nREASON=fetch_error\nDETAIL={exc}", flush=True)
        sys.exit(1)

    os.makedirs(os.path.dirname(HTML_FILE), exist_ok=True)
    with open(HTML_FILE, "w", encoding="utf-8") as f:
        f.write(html)
    info = validate(html)
    valid = 1 if info["valid"] else 0
    reason = "ok" if info["valid"] else "invalid_html"
    with open(STATUS_FILE, "w", encoding="utf-8") as f:
        f.write(
            f"VALIDATION={valid}\nREASON={reason}\nARTICLES={info['article_count']}\n"
            f"STARS={info['star_matches']}\nLANGS={info['lang_matches']}\n"
        )
    print(
        f"VALIDATION={valid}\nREASON={reason}\nARTICLES={info['article_count']}\n"
        f"STARS={info['star_matches']}\nLANGS={info['lang_matches']}",
        flush=True,
    )


if __name__ == "__main__":
    main()
