#!/usr/bin/env python3
"""Post-process the markdown files generated by mkdocs-gallery.

mkdocs-gallery hardcodes several elements that we don't want:

- A "Click here to download" note admonition at the top of every example page
- A download-buttons footer (Python source + Jupyter notebook links)
- A "Gallery generated by mkdocs-gallery" signature line
- "Out:" blocks showing script output (warnings, print statements)

This script strips all of those from the individual example pages and also
injects a zensical nav icon into the top-level gallery index.  The icon is
read from the ``icon:`` field in ``docs/examples/README.md`` frontmatter.

Run after:  mkdocs build -f mkdocs_gallery.yml
"""

import re
from pathlib import Path

GALLERY_DIR = Path("docs/generated/gallery")
README_SRC = Path("docs/examples/README.md")

# ── Resolve icon from source README frontmatter ───────────────────────────────

_readme = README_SRC.read_text(encoding="utf-8")
_icon_match = re.search(r"^icon:\s*(.+)$", _readme, re.MULTILINE)
ICON = _icon_match.group(1).strip() if _icon_match else "lucide/image"

# ── Top-level gallery index: inject nav icon ──────────────────────────────────

INDEX = GALLERY_DIR / "index.md"
content = INDEX.read_text(encoding="utf-8")
if not content.startswith("---"):
    INDEX.write_text(f"---\nicon: {ICON}\n---\n\n" + content, encoding="utf-8")

# ── Individual example pages: strip download noise and script output ──────────

for md_file in sorted(GALLERY_DIR.rglob("*.md")):
    if md_file.name == "index.md":
        continue

    content = md_file.read_text(encoding="utf-8")

    # 1. Remove the "Click here to download" note admonition.
    content = re.sub(
        r"^!!! note\n(?:[ \t]*\n|    .*\n)+",
        "",
        content,
        flags=re.MULTILINE,
    )

    # 2. Remove "Out:" blocks (script output captured by mkdocs-gallery).
    content = re.sub(
        r"Out:\n\{: \.mkd-glr-script-out \}\n\n```.*?```\n",
        "",
        content,
        flags=re.DOTALL,
    )

    # 3. Remove everything from the download_links anchor to end of file.
    content = re.sub(
        r"\n*<div id=\"download_links\"></div>.*\Z",
        "\n",
        content,
        flags=re.DOTALL,
    )

    # 4. Fallback: remove the mkdocs-gallery signature if still present.
    content = re.sub(
        r"\[Gallery generated by mkdocs-gallery\][^\n]*\n?",
        "",
        content,
    )

    md_file.write_text(content, encoding="utf-8")
    print(f"Patched {md_file.relative_to(GALLERY_DIR)}")
