import sys
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

def plot_crash_data(csv_file):
    # Read CSV data
    df = pd.read_csv(csv_file)
    
    # Group by A_lf and calculate statistics
    grouped = df.groupby('A_lf')['time_first_crash'].agg(['mean', 'std'])
    grouped = grouped.reset_index().sort_values('A_lf')

    grouped["up"]   = grouped['mean'] + grouped['std']
    grouped["down"] = grouped['mean'] - grouped['std']

    grouped.to_csv("sim.csv")
    
    # Create plot
    plt.figure(figsize=(10, 6))
    
    # Plot mean line
    plt.plot(grouped['A_lf'], grouped['mean'], 
             color='b',
             label='Mean Time to First Crash')
    
    # Plot standard deviation shading
    plt.fill_between(grouped['A_lf'],
                     grouped['mean'] - grouped['std'],
                     grouped['mean'] + grouped['std'],
                     color='b', alpha=0.2,
                     label='std')
    
    # Format plot
    plt.xlabel('A_lf Value', fontsize=12)
    plt.ylabel('Time to First Crash', fontsize=12)
    plt.title('Time to First Crash vs A_lf with Variability', fontsize=14)
    plt.grid(True, alpha=0.3)
    plt.legend()
    plt.tight_layout()
    
    # Save and show
    plt.savefig('plot.pdf', dpi=300)
    #plt.show()

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python plot.py <input_csv>")
        sys.exit(1)
    
    csv_path = sys.argv[1]
    plot_crash_data(csv_path)
