import re
import json
from pathlib import Path

text = Path('/tmp/gh_trending.html').read_text(errors='ignore')
blocks = re.split(r'<article class="Box-row">', text)[1:13]
repos = []
for b in blocks:
    href_m = re.search(r'href="/([^/]+/[^/\s"]+)"', b)
    if not href_m:
        continue
    full_name = href_m.group(1)
    if full_name.startswith('login?return_to='):
        fix = re.search(r'github.com/([^/]+/[^/\s"]+)"', b)
        if fix:
            full_name = fix.group(1)
    desc_m = re.search(r'<p[^>]*>\s*([^<]+)', b)
    desc = desc_m.group(1).strip() if desc_m else ''
    lang_m = re.search(r'<span[^>]+itemprop="programmingLanguage"[^>]*>([^<]+)', b)
    lang = lang_m.group(1).strip() if lang_m else ''
    stars_m = re.search(r'href="/' + re.escape(full_name.split('/')[0]) + r'/[^/]+/stargazers".*?>([0-9.,kKmM]+)', b)
    stars = stars_m.group(1).strip() if stars_m else ''
    forks_m = re.search(r'href="/' + re.escape(full_name.split('/')[0]) + r'/[^/]+/forks".*?>([0-9.,kKmM]+)', b)
    forks = forks_m.group(1).strip() if forks_m else ''
    delta_m = re.search(r'<span class="d-inline-block float-sm-right">(.*?)</span>', b, re.S)
    delta = ''
    if delta_m:
        inner = re.sub(r'<[^>]+>', '', delta_m.group(1))
        parts = [p.strip() for p in inner.split('\n') if p.strip()]
        delta = parts[0] if parts else ''
    repos.append({
        'full_name': full_name,
        'language': lang,
        'description': desc,
        'stars': stars,
        'forks': forks,
        'delta': delta,
    })
print(json.dumps(repos, ensure_ascii=False, indent=2))
