import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as col
from matplotlib.colors import ListedColormap
import matplotlib.patches as mpatches

# définition de couleurs
colors = ['orangered', 'dodgerblue', 'chartreuse', 'peru' ]
# création d'une colormap : 0 correspond à 'orangered', 1 à 'dodgerblue', etc.
jmr_cmap = ListedColormap(colors)



def lire_fichier(nom_fichier):
    """
    Lit un fichier et retourne ses lignes sous forme de liste.
    
    Args:
        chemin_fichier (str): Le chemin du fichier à lire.
        
    Returns:
        list: Liste contenant les lignes du fichier.
    """
    try:
        with open(nom_fichier, 'r', encoding='utf-8') as fichier:
            lignes = fichier.read()
        return lignes
    except FileNotFoundError:
        print(f"Erreur : Le fichier '{nom_fichier}' n'existe pas.")
        return []
    except Exception as e:
        print(f"Erreur inattendue : {e}")
        return []


def main():
    # Lecture du fichier
    nom_fichier = "mu.csv"  
    texte = lire_fichier(nom_fichier)
    lignes = texte.split('\n')
    print(lignes)


    # Créer les vecteurs de données
    notes_math = []
    notes_info = []
    etats = []

    for ligne in lignes:
        if len(ligne) != 0:
            colonnes = ligne.split(',')
            notes_math.append(float(colonnes[1]))
            notes_info.append(float(colonnes[2]))
            etats.append(colonnes[0])
                

    etats = np.array(etats, dtype=str)
    etats, indices_etats = np.unique(etats, return_inverse=True)
    # ['arizona' 'california' 'nevada' 'other']
    print(f"etats={etats}")
    # [0 1 2 3 1 0 ... 3 3 3 3]
    print(f"indices etats={indices_etats}")
    # [13.0, 17.0, 19, ... 5.0, 4.0, 7.0]
    print(f"notes en informatique={notes_info}")
    # [14.0, 18.0, ... 2.0, 6.0, 8.0]
    print(f"notes en mathématiques={notes_math}")

    moyenne_info = np.average(notes_info)
    moyenne_math = np.average(notes_math)
    # 13.53
    print(f"moyenne info={moyenne_info:5.2f}")
    # 12.56
    print(f"moyenne math={moyenne_math:5.2f}")


    plt.figure(figsize=(10, 8))

    # Graphique pour la répartition des notes en informatique
    plt.xlabel(f"notes informatiques, moyenne={moyenne_info:5.2f}")
    plt.ylabel("notes")
    plt.xlim(0,21)
    # retourne les valeurs uniques et leur nombre d'occurrences
    notes_info_echantillon, notes_info_occurrences = np.unique(notes_info, return_counts=True)
    plt.ylim(0,np.max(notes_info_occurrences)+1)
    plt.bar(notes_info_echantillon, notes_info_occurrences, color='skyblue', edgecolor='black')
    plt.show()

    # Graphique pour la répartition des notes en mathématiques
    plt.figure(figsize=(10, 8))
    plt.xlabel(f"notes mathématiques, moyenne={moyenne_math:5.2f}")
    plt.ylabel("notes")
    plt.xlim(0,21)
    # retourne les valeurs uniques et leur nombre d'occurrences
    notes_math_echantillon, notes_math_occurrences = np.unique(notes_math, return_counts=True)
    plt.ylim(0,np.max(notes_math_occurrences)+1)
    plt.bar(notes_math_echantillon, notes_math_occurrences, color='lightgreen', edgecolor='black')
    plt.show()

    # Graphique avec notes en informatique et notes en mathématiques
    plt.figure(figsize=(10, 8))
    ax = plt.axes()
    ax.set_facecolor("cornsilk")

    plt.xlabel("notes math")
    plt.ylabel("notes info")
    plt.xlim(0,22)
    plt.ylim(0,22)
    x=np.arange(1,20)
    y1=x
    y2=20-x
    plt.plot(x, y1, "silver", linestyle='--', alpha=0.6)
    plt.plot(x, y2, "silver", linestyle='--', alpha=0.6)
    # Création de la légende
    plt.scatter(notes_math, notes_info, c=indices_etats, cmap=jmr_cmap, s=50)
    patches = [mpatches.Patch(color=jmr_cmap(i), label=etats[i]) for i in range(len(etats))]
    plt.legend(handles=patches, title="État d'origine")

    plt.show()


if __name__ == "__main__":
    main()
