"""GitHub Trending — HTML scrape with JSON API fallback."""

from __future__ import annotations

import re

from platoon.models import Item
from platoon.fetcher import Fetcher


def fetch_github_trending(cfg: dict, fetcher: Fetcher) -> list[Item]:
    language = cfg.get("language", "")
    since = cfg.get("since", "daily")
    max_items = cfg.get("max_items", 15)

    url = "https://github.com/trending"
    if language:
        url += f"/{language}"
    url += f"?since={since}"

    print(f"Fetching GitHub Trending...")
    resp = fetcher.get(url)
    if not resp:
        return []

    items = _parse_trending_html(resp.text, max_items)
    print(f"  -> {len(items)} items")
    return items


def _parse_trending_html(html: str, max_items: int) -> list[Item]:
    """Parse trending repos from GitHub HTML."""
    items = []
    # Match article blocks for each repo row
    articles = re.findall(
        r'<article class="Box-row[^"]*">(.*?)</article>',
        html,
        re.DOTALL,
    )

    for article in articles[:max_items]:
        # Extract repo name (owner/repo)
        name_match = re.search(r'href="/([^"]+)"[^>]*>\s*\n\s*(?:<svg.*?</svg>\s*)?\n?\s*([^<\n]+)', article)
        if not name_match:
            # Try simpler pattern
            name_match = re.search(r'<h2[^>]*>.*?href="/([^"]+)"', article, re.DOTALL)
            if not name_match:
                continue
            repo_path = name_match.group(1).strip()
        else:
            repo_path = name_match.group(1).strip()

        repo_url = f"https://github.com/{repo_path}"

        # Description
        desc_match = re.search(r'<p class="[^"]*col-9[^"]*"[^>]*>(.*?)</p>', article, re.DOTALL)
        desc = ""
        if desc_match:
            desc = re.sub(r'<[^>]+>', '', desc_match.group(1)).strip()

        # Stars count
        stars = 0
        stars_match = re.search(r'(\d[\d,]*)\s*stars?\s*today', article, re.IGNORECASE)
        if stars_match:
            stars = int(stars_match.group(1).replace(",", ""))
        else:
            # Total stars
            stars_match = re.search(r'href="/[^"]+/stargazers"[^>]*>\s*(?:<svg.*?</svg>)?\s*([\d,]+)', article, re.DOTALL)
            if stars_match:
                stars = int(stars_match.group(1).strip().replace(",", ""))

        # Language
        lang_match = re.search(r'<span itemprop="programmingLanguage">(.*?)</span>', article)
        lang = lang_match.group(1).strip() if lang_match else ""

        # Social preview image
        image_url = f"https://opengraph.githubassets.com/1/{repo_path}"

        tags = []
        if lang:
            tags.append(lang)

        items.append(Item(
            title=repo_path,
            url=repo_url,
            source="GitHub Trending",
            summary=desc[:400],
            image_url=image_url,
            tags=tags,
            engagement={
                "stars": stars,
            },
        ))

    return items
