import matplotlib.pyplot as plt
import numpy as np
import typing
import os
from matplotlib.backends.backend_pdf import PdfPages


def generate_radar_plots(
    data, indexes: typing.Union[str, list] = None, pdf_path: str = "plots.pdf"
):
    """
    Generate radar plots for individuals selected by indices. And save them as
     PNG files.
    :param data: DataFrame containing the criteria data.
    :param indexes: List of index values corresponding to the rows to display
     (if None, all rows are displayed).
    :param pdf_path: Path of the pdf file that will be generated. Default is
     'plots'
    :return: None. Generate a pdf file with radar plots.
    """
    if not str.endswith(pdf_path, ".pdf"):
        raise ValueError("Arg 'pdf_path' must end with '.pdf'")
    path = pdf_path.split("/")
    filename = path.pop(-1)
    path = "/".join(path)
    os.makedirs(path, exist_ok=True)
    normalized_data = (data - data.min()) / (data.max() - data.min())
    with PdfPages(f"{path}/{filename}") as pdf:
        for i in indexes:
            values = normalized_data.loc[i].tolist()
            values += values[:1]  # pour fermer le polygone
            num_vars = len(data.columns)
            angles = np.linspace(
                0, 2 * np.pi, num_vars, endpoint=False
            ).tolist()
            angles += angles[:1]
            fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
            ax.plot(angles, values, linewidth=2, linestyle="solid")
            ax.fill(angles, values, alpha=0.3)
            ax.set_xticks(angles[:-1])
            ax.set_title(f"Radar plot for {i}", size=14, pad=20)
            pdf.savefig(fig)
            plt.close(fig)
