"""A program to plot a psd such as one generated by sgnl-reference-psd"""

# Copyright (C) 2012 Chad Hanna
# Copyright (C) 2024 Yun-Jing Huang


import os
from argparse import ArgumentParser

from sgnl.plots.util import set_matplotlib_cache_directory

set_matplotlib_cache_directory()
import matplotlib  # noqa: E402

from sgnl.plots.psd import plot_psds  # noqa: E402
from sgnl.psd import read_psd  # noqa: E402

matplotlib.rcParams.update(
    {
        "font.size": 10.0,
        "axes.titlesize": 10.0,
        "axes.labelsize": 10.0,
        "xtick.labelsize": 8.0,
        "ytick.labelsize": 8.0,
        "legend.fontsize": 8.0,
        "figure.dpi": 300,
        "savefig.dpi": 300,
        "text.usetex": False,
        "path.simplify": True,
    }
)


def parse_command_line():
    parser = ArgumentParser()
    parser.add_argument("filenames", nargs="+")
    parser.add_argument(
        "-o",
        "--output",
        help="Set plot filename (default = replace input file's extension with .png).",
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="Be verbose.")
    options = parser.parse_args()
    filenames = options.filenames

    if not filenames:
        raise ValueError("must supply at least one input filename")
    if options.output and len(filenames) > 1:
        raise ValueError("must supply only one input file when setting --output")

    return options


def main():
    options = parse_command_line()

    for fname in options.filenames:
        if options.output:
            outname = options.output
        else:
            outname = os.path.join(os.path.splitext(fname)[0], ".png")

        fig = plot_psds(read_psd(fname, verbose=options.verbose), plot_width=2400)
        fig.savefig(outname)
