"""Plot export utilities."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from impakt.plot.engine import PlotEngine
from impakt.plot.spec import PlotSpec


def export_plot(
    spec: PlotSpec,
    path: str | Path,
    format: str | None = None,
    scale: float = 2.0,
) -> None:
    """Export a plot to a file.

    Args:
        spec: Plot specification.
        path: Output file path.
        format: Image format. Inferred from extension if not provided.
        scale: Resolution multiplier for raster formats.
    """
    path = Path(path)

    if format is None:
        ext = path.suffix.lower().lstrip(".")
        format_map = {
            "png": "png",
            "jpg": "jpeg",
            "jpeg": "jpeg",
            "svg": "svg",
            "pdf": "pdf",
            "html": "html",
        }
        format = format_map.get(ext, "png")

    engine = PlotEngine()

    if format == "html":
        html = engine.to_html(spec)
        path.write_text(html, encoding="utf-8")
    else:
        image_bytes = engine.to_image(spec, format=format, scale=scale)
        path.write_bytes(image_bytes)
