#!/usr/bin/env python3

from __future__ import annotations

import argparse
import base64
import subprocess
from pathlib import Path


def render_mermaid(input_path: Path, output_path: Path, theme: str) -> None:
    code = input_path.read_text(encoding="utf-8")
    encoded = base64.b64encode(code.encode("utf-8")).decode("ascii")
    url = f"https://mermaid.ink/pdf/{encoded}?fit&theme={theme}&bgColor=!white"
    output_path.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run(
        [
            "curl",
            "-fsSL",
            "-A",
            "Mozilla/5.0",
            "--retry",
            "4",
            "--retry-all-errors",
            url,
            "-o",
            str(output_path),
        ],
        check=True,
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Render Mermaid diagrams to PDF via mermaid.ink")
    parser.add_argument("inputs", nargs="+", help="Input .mmd files")
    parser.add_argument("--output-dir", required=True, help="Directory for rendered PDFs")
    parser.add_argument("--theme", default="neutral", help="Mermaid theme")
    args = parser.parse_args()

    output_dir = Path(args.output_dir)
    for item in args.inputs:
        input_path = Path(item)
        output_path = output_dir / f"{input_path.stem}.pdf"
        render_mermaid(input_path, output_path, args.theme)
        print(f"rendered {input_path} -> {output_path}")


if __name__ == "__main__":
    main()
