#!/usr/bin/env python3
import re
import subprocess
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SOURCE_DIR = ROOT / "assets" / "figures" / "source" / "dot-er"
OUTPUT_DIR = ROOT / "assets" / "figures" / "er"
POSITION_SCALE = 100
DPI = 220


def scale_positions(dot_source: str) -> str:
    return re.sub(
        r'pos="([\d.-]+),([\d.-]+)!"',
        lambda match: (
            f'pos="{float(match.group(1)) * POSITION_SCALE},'
            f'{float(match.group(2)) * POSITION_SCALE}!"'
        ),
        dot_source,
    )


def render(dot_path: Path) -> None:
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory() as td:
        scaled_dot = Path(td) / dot_path.name
        scaled_dot.write_text(scale_positions(dot_path.read_text(encoding="utf-8")), encoding="utf-8")

        stem = dot_path.stem
        subprocess.run(
            ["neato", "-n2", "-Tpng", f"-Gdpi={DPI}", str(scaled_dot), "-o", str(OUTPUT_DIR / f"{stem}.png")],
            check=True,
        )
        subprocess.run(
            ["neato", "-n2", "-Tpdf", str(scaled_dot), "-o", str(OUTPUT_DIR / f"{stem}.pdf")],
            check=True,
        )


def main() -> None:
    for dot_path in sorted(SOURCE_DIR.glob("*.dot")):
        render(dot_path)


if __name__ == "__main__":
    main()
