"""Plot m1 vs time from one or more result files."""

from pathlib import Path

import numpy as np
from matplotlib import pyplot as plt

from ..io import RunResults, load_results
from .utils import get_cli_args


def plot_m1_vs_time(
    *files: Path, image_filepath: Path | str | None = None, show: bool = False
):
    """
    Plot the results from the given files.

    Args:
        *files: Paths to the result files.
        image_filepath: Path to the output image file.
            if None, the image will not be saved.
        show: display the graph in a graphical window.
    """
    fig, ax = plt.subplots()
    for file in files:
        print(f"Processing file: {file}")
        result: RunResults = load_results(file)
        xyz_average: np.ndarray = np.array(result.get_record("xyz_average"))
        ax.plot(xyz_average[:, 0], xyz_average[:, 1], label=file)

    ax.set_xlabel("time")
    ax.set_ylabel(r"$<m_1>$")
    ax.grid()
    ax.legend()
    ax.set_title(r"Space average of $m_1$ according to time")

    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
    """Parse CLI arguments and call the plot function."""
    args = get_cli_args(
        description=__doc__,
        default_image_filepath=Path("m1_vs_time.png"),
    )

    plot_m1_vs_time(
        *args.files,
        image_filepath=args.image_filepath,
        show=args.show,
    )
