import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import sys
from matplotlib.colors import LogNorm
import matplotlib.ticker as ticker

sns.set_theme(style="whitegrid", context="talk")
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['figure.dpi'] = 300

def load_data(filename):
    try:
        df = pd.read_csv(filename)
        
        df['Label'] = (
            "k=" + df['k'].astype(str) + 
            " | Wc=" + df['wc'].astype(str) + 
            " | Wr=" + df['wr'].astype(str)
        )
        
        df = df.sort_values(by=['k', 'wc', 'wr'])
        
        return df
    except FileNotFoundError:
        print(f"Erreur : Le fichier '{filename}' est introuvable.")
        sys.exit(1)

def plot_1_waterfall_zoomed(df):
    print("   -> Génération du Waterfall...")
    plt.figure(figsize=(14, 9))
    
    df_zoom = df[df['ber'] > 0].copy()
    
    if df_zoom.empty:
        print("    Pas d'erreurs trouvées, impossible de tracer.")
        return

    sns.lineplot(
        data=df_zoom, 
        x='p', 
        y='ber', 
        hue='Label', 
        style='Label',
        markers=True, 
        dashes=False, 
        linewidth=2.5, 
        palette="turbo",
        markersize=9
    )

    plt.yscale('log')
    ax = plt.gca()
    ax.yaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=12))
    
    plt.title("Vue Globale : Performance des configurations", fontweight='bold', pad=20)
    plt.ylabel("BER [Log Scale]", labelpad=15)
    plt.xlabel("Bruit du Canal (p)", labelpad=15)
    plt.grid(True, which="both", ls="-", alpha=0.3)
    
    plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0, title="Configuration", fontsize='x-small')
    
    plt.tight_layout()
    plt.savefig("Final_1_Waterfall.png")

def plot_2_ranking_bars(df):
    print("   -> Génération du Classement...")
    
    means = df.groupby('p')['ber'].mean()
    target_p = means[means > 0.0001].first_valid_index()
    
    if target_p is None:
        target_p = df['p'].max()

    subset = df[df['p'] == target_p].sort_values('ber', ascending=True)

    plt.figure(figsize=(12, max(6, len(subset)*0.4))) 
    
    barplot = sns.barplot(
        data=subset, 
        y='Label', 
        x='ber', 
        palette="viridis", 
        edgecolor=".2"
    )
    
    plt.xscale('log')
    plt.title(f"Robustesse p={target_p:.3f} (Gauche = Meilleur)", fontweight='bold', pad=20)
    plt.xlabel("BER", labelpad=10)
    plt.ylabel("") 
    
    for i, container in enumerate(barplot.containers):
        barplot.bar_label(container, fmt='%.1e', padding=5, fontsize=11)
        
    plt.grid(True, axis='x', which="both", ls="--", alpha=0.5)
    plt.tight_layout()
    plt.savefig("Final_2_Classement.png")

def plot_3_heatmap_gradient(df):
    print("   -> Génération de la Heatmap...")
    
    pivot = df.pivot(index="Label", columns="p", values="ber")
    
    pivot_log = pivot.replace(0, 1e-9) 
    
    plt.figure(figsize=(16, max(6, len(pivot)*0.5))) 
    
    ax = sns.heatmap(
        pivot_log, 
        cmap="Spectral_r", 
        norm=LogNorm(vmin=1e-5, vmax=1),
        cbar_kws={'label': 'BER (Log Scale)'},
        linewidths=0.5,
        linecolor='white'
    )
    
    plt.title("Résistance (Bleu=Zone de Confort, Rouge=Zone d'Échec)", fontweight='bold', pad=20)
    plt.xlabel("Bruit du Canal (p)", labelpad=10)
    plt.ylabel("")
    
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig("Final_3_Heatmap.png")

if __name__ == "__main__":
    print("Démarrage de l'analyse graphique finale...")
    
    df = load_data("ldpc_analysis_results.csv")
    
    plot_1_waterfall_zoomed(df)
    plot_2_ranking_bars(df)
    plot_3_heatmap_gradient(df)
    
    print("\nTerminé ! Trois images générées :")
    print("   1. Final_1_Waterfall.png (Courbes détaillées)")
    print("   2. Final_2_Classement.png (Comparatif barres)")
    print("   3. Final_3_Heatmap.png (Vision globale couleur)")
