#!/usr/bin/env python3
"""
Parse awesome-jellyfin README.md into a structured plugin catalog
and optionally build a Jellyfin plugin-repository manifest.
"""

import json
import re
import sys
from pathlib import Path
from urllib.parse import urlparse

README = Path(__file__).with_name("README.md")
OUT_CATALOG = Path(__file__).with_name("plugin-catalog.json")
OUT_MANIFEST = Path(__file__).with_name("plugin-manifest.json")

# Sections in README.md that list Jellyfin *plugins*.
PLUGIN_SECTIONS = {
    "UI & Customization": "ui-customization",
    "Collections & Playlists": "collections-playlists",
    "Playback": "playback",
    "Integration & Sync": "integration-sync",
    "Notifications": "notifications",
    "Authentication": "authentication",
    "Library Management": "library-management",
    "Metadata Providers": "metadata-providers",
}

# Markdown list item regex supporting nested leading whitespace and GitHub links.
LIST_ITEM_RE = re.compile(
    r"^\s*-\s*\[([^\]]+)\]\((https?://[^\)]+)\)\s*-?\s*(.*)$"
)


def parse_readme(path: Path) -> list[dict]:
    content = path.read_text(encoding="utf-8")
    lines = content.splitlines()

    plugins: list[dict] = []
    current_category = None
    current_category_slug = None

    for raw_line in lines:
        line = raw_line.rstrip()

        # Detect plugin category headings (### <emoji> <category>)
        if line.startswith("### "):
            title = line.removeprefix("### ").strip()
            # Strip leading emoji + whitespace so "🎨 UI & Customization" becomes "UI & Customization"
            title = re.sub(r"^[\U0001F300-\U0001FAFF\u2600-\u26FF\u2700-\u27BF]+\s*", "", title)
            if title in PLUGIN_SECTIONS:
                current_category = title
                current_category_slug = PLUGIN_SECTIONS[title]
            else:
                current_category = None
                current_category_slug = None
            continue

        if current_category is None:
            continue

        match = LIST_ITEM_RE.match(line)
        if not match:
            continue

        name, url, description = match.groups()
        description = description.strip()

        # Extract status badges from the description tail.
        tags = []
        for badge in ("🔰 Official", "🔹 Beta", "🔸 Stale", "🔺 Paid"):
            if badge in description:
                tags.append(badge.strip().split()[-1].lower())
                description = description.replace(badge, "").strip()

        # Try to derive repo owner/name from GitHub URL.
        repo_owner = repo_name = None
        parsed = urlparse(url)
        if parsed.netloc == "github.com":
            parts = parsed.path.strip("/").split("/")
            if len(parts) >= 2:
                repo_owner, repo_name = parts[0], parts[1]

        plugins.append(
            {
                "name": name.strip(),
                "url": url,
                "description": description.strip("- "),
                "category": current_category,
                "categorySlug": current_category_slug,
                "tags": tags,
                "github": {"owner": repo_owner, "repo": repo_name} if repo_owner else None,
            }
        )

    return plugins


def build_jellyfin_manifest(plugins: list[dict]) -> list[dict]:
    """
    Build a skeleton Jellyfin plugin-repository manifest.
    Version/release information must be filled in after fetching
    each repository's releases (see fetch_releases.py).
    """
    manifest = []
    for p in plugins:
        if not p.get("github"):
            continue
        gh = p["github"]
        manifest.append(
            {
                "category": p["category"],
                "guid": f"awesome-jellyfin-{gh['owner']}-{gh['repo']}",
                "name": p["name"],
                "description": p["description"],
                "overview": p["description"],
                "owner": gh["owner"],
                "imageUrl": "",
                "versions": [],
            }
        )
    return manifest


def main() -> int:
    plugins = parse_readme(README)
    OUT_CATALOG.write_text(
        json.dumps(plugins, indent=2, ensure_ascii=False), encoding="utf-8"
    )
    print(f"Wrote {len(plugins)} plugins to {OUT_CATALOG}")

    manifest = build_jellyfin_manifest(plugins)
    OUT_MANIFEST.write_text(
        json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8"
    )
    print(f"Wrote skeleton manifest for {len(manifest)} plugins to {OUT_MANIFEST}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
