"""Plot the magnetization vs temperature and determine the Curie temperature."""

from pathlib import Path

import matplotlib
import matplotlib.pyplot as plt

from .process import MagTempData


def plot_m1_vs_T(
    mag_data: MagTempData,
    image_filepath: Path | str | None = None,
    show: bool = False,
):
    """
    Plots the data (T, <m_1>).

    Interpolates the values, calculates the Curie temperature, exports to PNG.

    Args:
        mag_data: Magnetization data object
        image_filepath: Path to save the image
          if None, the image will not be saved.
        show: display the graph in a graphical window
    """
    print(f"T_Curie = {mag_data.T_Curie:.0f} K")
    if not show:
        matplotlib.use("Agg")  # Use non-interactive backend

    fig, ax = plt.subplots()
    fig.suptitle("Average magnetization vs Temperature")
    params = mag_data.params
    ax.set_title(
        params["element"]
        + rf", ${params['Jx']}\times{params['Jy']}\times{params['Jz']}$"
        rf" ($dx = ${params['dx']})",
        fontdict={"size": 10},
    )
    ax.plot(
        mag_data.temperature,
        mag_data.m1_mean,
        "o",
        markerfacecolor="white",
        label=f"{params['solver']} computations",
    )
    ax.plot(
        mag_data.temperature_interp,
        mag_data.interp(mag_data.temperature_interp),
        label="interpolation (PCHIP)",
    )
    ax.annotate(
        "$T_{{Curie}} = {:.0f} K$".format(mag_data.T_Curie),
        xy=(mag_data.T_Curie, 0.1),
        xytext=(mag_data.T_Curie + 20, 0.1 + 0.01),
    )
    # Draw lines to indicate T_Curie
    ax_ymin = ax.get_ylim()[0]
    ax_ymax = ax.get_ylim()[1]
    y_T_Curie = (0.1 - ax_ymin) / (ax_ymax - ax_ymin)
    ax.axvline(x=mag_data.T_Curie, ymax=y_T_Curie, color="k", linestyle="--")
    ax_xmin = ax.get_xlim()[0]
    x_T_Curie = (mag_data.T_Curie - ax_xmin) / (ax.get_xlim()[1] - ax_xmin)
    ax.axhline(y=0.1, xmax=x_T_Curie, color="k", linestyle="--")
    # Mark the Curie point
    ax.plot(mag_data.T_Curie, 0.1, color="k", marker="s", markerfacecolor="white")
    ax.set_xlabel("Temperature [K]")
    ax.set_ylabel("Magnetization")
    ax.grid()
    ax.legend()

    if show:
        plt.show()

    if image_filepath is not None:
        fig.savefig(image_filepath, dpi=300)
        print(f"Written to {image_filepath}")


def main():  # pragma: no cover
    """Parses the command line to execute processing functions."""
    from .utils import get_cli_args

    args = get_cli_args(
        description=__doc__,
        default_image_filepath=Path("m1_vs_T.png"),
    )

    mag_data = MagTempData(*args.files)
    plot_m1_vs_T(mag_data, image_filepath=args.image_filepath, show=args.show)
