#!/usr/bin/env python3
"""Download Reveal.js dist files into vendor/reveal.js/."""

from __future__ import annotations

import shutil
import sys
import tempfile
import urllib.error
import urllib.request
import zipfile
from pathlib import Path

REVEAL_VERSION = "5.1.0"
REVEAL_URL = (
    f"https://github.com/hakimel/reveal.js/archive/refs/tags/{REVEAL_VERSION}.zip"
)
ROOT = Path(__file__).resolve().parent.parent
VENDOR_DIST = ROOT / "vendor" / "reveal.js" / "dist"

# Paths inside the release archive (prefix reveal.js-{version}/ is added at runtime)
DIST_FILES = (
    "dist/reveal.js",
    "dist/reveal.css",
    "dist/reset.css",
    "dist/theme/night.css",
)


def fetch_reveal() -> None:
    VENDOR_DIST.mkdir(parents=True, exist_ok=True)

    with tempfile.TemporaryDirectory() as tmp_dir:
        zip_path = Path(tmp_dir) / "reveal.zip"
        print(f"→ Lade Reveal.js {REVEAL_VERSION} …")
        try:
            urllib.request.urlretrieve(REVEAL_URL, zip_path)
        except urllib.error.URLError as exc:
            raise SystemExit(f"Download fehlgeschlagen: {exc}") from exc

        prefix = f"reveal.js-{REVEAL_VERSION}/"
        with zipfile.ZipFile(zip_path) as archive:
            for rel_path in DIST_FILES:
                archive_path = prefix + rel_path
                dest = VENDOR_DIST / rel_path.removeprefix("dist/")
                dest.parent.mkdir(parents=True, exist_ok=True)
                try:
                    with archive.open(archive_path) as src, dest.open("wb") as out:
                        shutil.copyfileobj(src, out)
                except KeyError as exc:
                    raise SystemExit(
                        f"Erwartete Datei fehlt im Archiv: {archive_path}"
                    ) from exc

    print(f"→ Reveal.js nach {VENDOR_DIST.relative_to(ROOT)}/ installiert")


def main() -> None:
    fetch_reveal()


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