#!/usr/bin/env python3
"""
Scan Playlists/*.html, extract title + track count, inject cards into playlists.html.
Run after adding or updating any playlist page.
"""
import re
from pathlib import Path

HERE = Path(__file__).parent
HUB = HERE / "playlists.html"
EXCLUDE = {"playlists.html"}

entries = []

for html_file in sorted(HERE.glob("*.html")):
    if html_file.name in EXCLUDE:
        continue

    text = html_file.read_text(encoding="utf-8")

    m = re.search(r"<h1[^>]*>(.*?)</h1>", text, re.IGNORECASE | re.DOTALL)
    title = re.sub(r"<[^>]+>", "", m.group(1)).strip() if m else html_file.stem

    tracks = len(re.findall(r'class="track-card"', text))

    entries.append({"slug": html_file.stem, "title": title, "tracks": tracks})

entries.sort(key=lambda e: e["title"].lower())

# Build card HTML
cards = "\n".join(
    f'        <a href="{e["slug"]}.html" class="playlist-card">\n'
    f'            <div class="playlist-name">{e["title"]}</div>\n'
    f'            <div class="track-count">{e["tracks"]} tracks</div>\n'
    f'        </a>'
    for e in entries
)

total = sum(e["tracks"] for e in entries)
subtitle = f'{len(entries)} playlists &bull; {total} tracks &bull; Faerie Fire Collection'

hub = HUB.read_text(encoding="utf-8")

hub = re.sub(
    r"<!-- PLAYLIST-CARDS-START -->.*?<!-- PLAYLIST-CARDS-END -->",
    f"<!-- PLAYLIST-CARDS-START -->\n{cards}\n        <!-- PLAYLIST-CARDS-END -->",
    hub, flags=re.DOTALL
)

hub = re.sub(
    r"<!-- SUBTITLE-START -->.*?<!-- SUBTITLE-END -->",
    f'<!-- SUBTITLE-START -->\n        <p class="subtitle">{subtitle}</p>\n        <!-- SUBTITLE-END -->',
    hub, flags=re.DOTALL
)

HUB.write_text(hub, encoding="utf-8")
print(f"Updated playlists.html — {len(entries)} playlist(s), {total} tracks")
for e in entries:
    print(f"  {e['slug']} — {e['title']} ({e['tracks']} tracks)")
