"""Shared plotting helpers for the literal MATLAB-to-Python conversions."""

from __future__ import annotations

from pathlib import Path
import os

import matplotlib.pyplot as plt
from cycler import cycler


CO = [
    (0.0, 0.0, 1.0),
    (0.0, 0.5, 0.0),
    (1.0, 0.0, 0.0),
    (0.0, 0.75, 0.75),
    (0.75, 0.0, 0.75),
    (0.75, 0.75, 0.0),
    (0.25, 0.25, 0.25),
]


def scaled_figsize(width_px: float, height_px: float, dpi: float = 100.0) -> tuple[float, float]:
    """Convert the MATLAB pixel size to inches and scale it to fit a normal plot window."""
    width = width_px / dpi
    height = height_px / dpi
    scale = min(1.0, 8.0 / width, 6.5 / height)
    return width * scale, height * scale


def matlab_figure(number: int | None, width_px: float, height_px: float):
    """Create or clear a Matplotlib figure using the scaled MATLAB figure dimensions."""
    fig = plt.figure(num=number, figsize=scaled_figsize(width_px, height_px), clear=True)
    fig.set_dpi(100)
    return fig


def set_color_order(ax) -> None:
    """Apply the MATLAB defaultAxesColorOrder used in the original scripts."""
    ax.set_prop_cycle(cycler(color=CO))


def style_axes(ax, fontsize: float, fontweight: str = "bold") -> None:
    """Apply MATLAB-like bold axis formatting."""
    ax.tick_params(axis="both", labelsize=fontsize)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight(fontweight)
    if hasattr(ax, "get_zticklabels"):
        for label in ax.get_zticklabels():
            label.set_fontweight(fontweight)
            label.set_fontsize(fontsize)
    ax.xaxis.label.set_fontsize(fontsize)
    ax.yaxis.label.set_fontsize(fontsize)
    ax.xaxis.label.set_fontweight(fontweight)
    ax.yaxis.label.set_fontweight(fontweight)
    if hasattr(ax, "zaxis"):
        ax.zaxis.label.set_fontsize(fontsize)
        ax.zaxis.label.set_fontweight(fontweight)


def finish_figure(fig, filename: str | None = None) -> None:
    """Save only when FIG9_SAVE_DIR is set; otherwise leave the figure open for plt.show()."""
    save_dir = os.getenv("FIG9_SAVE_DIR")
    if save_dir and filename:
        path = Path(save_dir)
        path.mkdir(parents=True, exist_ok=True)
        fig.savefig(path / filename, bbox_inches="tight")
