import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os

def plot_core_algo():
    if not os.path.exists("results/algo_comparison.csv"):
        print("Core algo results not found.")
        return

    df = pd.read_csv("results/algo_comparison.csv")
    
    # 1. Approximation Ratio Distribution (Boxplot)
    # Filter valid ratios (where opt was computed)
    df_ratios = df[df['ls_ratio'] != -1]
    
    if not df_ratios.empty:
        plt.figure(figsize=(10, 6))
        # Melt for seaborn
        df_melt = df_ratios.melt(id_vars=['m', 'n'], value_vars=['ls_ratio', 'lpt_ratio'], 
                                 var_name='Algorithm', value_name='Ratio')
        
        sns.boxplot(data=df_melt, x='m', y='Ratio', hue='Algorithm')
        plt.title('Approximation Ratio Distribution by Machine Count (m)')
        plt.ylabel('Approximation Ratio (Greedy / Optimal)')
        plt.xlabel('Number of Machines (m)')
        plt.savefig('results/ratio_boxplot.png')
        plt.close()
        
        # Plot vs N
        plt.figure(figsize=(10, 6))
        sns.lineplot(data=df_melt, x='n', y='Ratio', hue='Algorithm', style='m', markers=True)
        plt.title('Approximation Ratio vs Job Count (n)')
        plt.savefig('results/ratio_vs_n.png')
        plt.close()

    # 2. Running Time Comparison
    plt.figure(figsize=(10, 6))
    df_time = df.groupby(['n', 'm']).mean().reset_index()
    # Log scale for time
    plt.plot(df_time['n'], df_time['ls_time'], label='List Scheduling', marker='o')
    plt.plot(df_time['n'], df_time['lpt_time'], label='LPT', marker='x')
    
    # Only plot Opt time where available (it drops to 0/empty for large n)
    df_opt = df_time[df_time['opt_time'] > 0]
    if not df_opt.empty:
        plt.plot(df_opt['n'], df_opt['opt_time'], label='Optimal (B&B)', marker='s')
        
    plt.yscale('log')
    plt.title('Average Running Time vs Input Size (n)')
    plt.ylabel('Time (microseconds)')
    plt.xlabel('Number of Jobs (n)')
    plt.legend()
    plt.savefig('results/time_comparison.png')
    plt.close()

if __name__ == "__main__":
    plot_core_algo()
