"""Select font style for Matplotlib plots."""

import os
import shutil
import subprocess

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# Set path to matlablotlib cache; modify to suit your own use case; be careful!!!
CACHEPATH = os.path.join(os.path.expanduser("~"), ".cache/matplotlib")

SERIF_FONT = "STIXTwoText-Regular.otf"
SANS_SERIF_FONT = "SourceSansPro-Regular.otf"


def get_font_path(font_name: str) -> str:
    """Get the path to a font file."""

    fonts = subprocess.run(
        ["fc-list"],  # Run the `fc-list` command
        stdout=subprocess.PIPE,  # Capture the standard output
        text=True,  # Decode output as text (str, not bytes)
    )

    matched_fonts = [line for line in fonts.stdout.splitlines() if font_name in line]

    if not matched_fonts:
        raise SystemExit(f"Font {font_name} could not found on your system.")

    # We arbitrarily choosing the first matched font because we are expecting only one
    # font to match if there is more than one we would have to handle that case later
    font_path = matched_fonts[0].split(":")[0]

    return font_path


def set_font_style(textfont: str = "sans-serif") -> None:
    """
    Sets the matplotlib plot style with specified font family.

    Args:
        textfont: "serif" or "sans-serif". Defaults to "sans-serif".
    """
    shutil.rmtree(CACHEPATH)  # First clear matplotlib cache to avoid surprises

    serif_font_path = get_font_path(SERIF_FONT)
    sans_serif_font_path = get_font_path(SANS_SERIF_FONT)

    if textfont == "serif":
        if os.path.exists(serif_font_path):
            fm.fontManager.addfont(serif_font_path)
            plt.rcParams.update({"font.family": "STIX Two Text"})
        else:
            print(
                f"Warning: Serif font not found at {serif_font_path}. "
                "Using default font."
            )
    elif textfont == "sans-serif":
        if os.path.exists(sans_serif_font_path):
            fm.fontManager.addfont(sans_serif_font_path)
            plt.rcParams.update({"font.family": "Source Sans Pro"})
        else:
            print(
                f"Warning: Sans-serif font not found at {sans_serif_font_path}. "
                "Using default font."
            )
    else:
        print("Warning: Invalid textfont argument. Using default font.")

    # Set other constants (e.g., font sizes)
    plt.rcParams.update(
        {
            "font.size": 12,  # Example font size
            "axes.labelsize": 14,
            "axes.titlesize": 16,
            "xtick.labelsize": 12,
            "ytick.labelsize": 12,
            "legend.fontsize": 12,
        }
    )
