import pandas as pd
import matplotlib.pyplot as plt
import glob
import os
import sys

# Find CSV files using glob
def load_latest_csv(pattern):
    """Load the most recent CSV file matching the pattern"""
    files = glob.glob(pattern)
    if not files:
        print(f"Warning: No files found matching '{pattern}'")
        return None
    # Sort by modification time, get the latest
    latest_file = max(files, key=os.path.getmtime)
    print(f"Loading: {latest_file}")
    return pd.read_csv(latest_file)

# Determine which load to analyze
if len(sys.argv) > 1:
    load_type = sys.argv[1].upper()
else:
    print("Usage: python graphing_single.py [LOW|MEDIUM|HIGH]")
    print("Defaulting to LOW_LOAD...")
    load_type = "LOW"

# Validate load type
if load_type not in ["LOW", "MEDIUM", "HIGH"]:
    print(f"Error: Invalid load type '{load_type}'. Must be LOW, MEDIUM, or HIGH.")
    exit(1)

# Load the specified data
print(f"Looking for {load_type}_LOAD analysis files...")
pattern = f'analysis/{load_type}_LOAD_*.csv'
data = load_latest_csv(pattern)

if data is None:
    print(f"\nError: No {load_type}_LOAD analysis files found!")
    print("Please run the batch analysis first.")
    exit(1)

# Print available columns for debugging
print(f"\nAvailable columns in {load_type}_LOAD CSV:")
print(data.columns.tolist())

# Create output directory for graphs
os.makedirs('graphs', exist_ok=True)

# Determine the run column name (could be 'Run' or 'Execução')
run_col = 'Run' if 'Run' in data.columns else 'Execução'

# Load name for titles
load_name = load_type.capitalize()
colors = {'LOW': 'green', 'MEDIUM': 'orange', 'HIGH': 'red'}
color = colors[load_type]

# 1. Gráfico: Run-by-Run Dwelling Time
plt.figure(figsize=(12, 6))
plt.plot(data[run_col], data['TempoMédioSistema'], marker='o', color=color, linewidth=2, markersize=6)
plt.fill_between(data[run_col], data['TempoMínimoSistema'], data['TempoMáximoSistema'], alpha=0.2, color=color)
plt.ylabel('Tempo no Sistema (s)')
plt.xlabel('Run Number')
plt.title(f'Tempo no Sistema por Execução - Carga {load_name}')
plt.grid(alpha=0.3)
plt.legend(['Média', 'Min-Max Range'])
plt.savefig(f'graphs/{load_type.lower()}_dwelling_time_runs.png', dpi=300, bbox_inches='tight')
print(f"\nGraph saved: graphs/{load_type.lower()}_dwelling_time_runs.png")
plt.close()

# 2. Gráfico: Run-by-Run Completion Rate
plt.figure(figsize=(12, 6))
plt.plot(data[run_col], data['TaxaConclusão'], marker='o', color=color, linewidth=2, markersize=6)
plt.axhline(y=data['TaxaConclusão'].mean(), color='black', linestyle='--', label=f'Média: {data["TaxaConclusão"].mean():.1f}%')
plt.ylabel('Taxa de Conclusão (%)')
plt.xlabel('Run Number')
plt.title(f'Taxa de Conclusão por Execução - Carga {load_name}')
plt.ylim(0, 105)
plt.grid(alpha=0.3)
plt.legend()
plt.savefig(f'graphs/{load_type.lower()}_completion_rate_runs.png', dpi=300, bbox_inches='tight')
print(f"Graph saved: graphs/{load_type.lower()}_completion_rate_runs.png")
plt.close()

# 3. Gráfico: Run-by-Run Waiting Time
plt.figure(figsize=(12, 6))
plt.plot(data[run_col], data['TempoMédioEspera'], marker='o', color=color, linewidth=2, markersize=6)
plt.ylabel('Tempo de Espera (s)')
plt.xlabel('Run Number')
plt.title(f'Tempo Médio de Espera por Execução - Carga {load_name}')
plt.grid(alpha=0.3)
plt.savefig(f'graphs/{load_type.lower()}_waiting_time_runs.png', dpi=300, bbox_inches='tight')
print(f"Graph saved: graphs/{load_type.lower()}_waiting_time_runs.png")
plt.close()

# 4. Gráfico: Vehicles Generated vs Completed
plt.figure(figsize=(10, 6))
x = range(len(data))
width = 0.35
plt.bar([i - width/2 for i in x], data['VeículosGerados'], width, label='Gerados', color='lightblue', alpha=0.8)
plt.bar([i + width/2 for i in x], data['VeículosCompletados'], width, label='Concluídos', color=color, alpha=0.8)
plt.ylabel('Número de Veículos')
plt.xlabel('Run Number')
plt.title(f'Veículos Gerados vs Concluídos - Carga {load_name}')
plt.xticks(x, data[run_col])
plt.legend()
plt.grid(axis='y', alpha=0.3)
plt.savefig(f'graphs/{load_type.lower()}_vehicles_comparison.png', dpi=300, bbox_inches='tight')
print(f"Graph saved: graphs/{load_type.lower()}_vehicles_comparison.png")
plt.close()

# 5. Gráfico: Summary Statistics (4-panel)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))

# Panel 1: Dwelling Time Statistics
metrics = ['Média', 'Mínimo', 'Máximo', 'Desvio\nPadrão']
values = [
    data['TempoMédioSistema'].mean(),
    data['TempoMínimoSistema'].min(),
    data['TempoMáximoSistema'].max(),
    data['TempoMédioSistema'].std()
]
ax1.bar(metrics, values, color=[color, 'lightblue', 'darkblue', 'gray'])
ax1.set_title('Estatísticas de Tempo no Sistema')
ax1.set_ylabel('Tempo (s)')
ax1.grid(axis='y', alpha=0.3)
for i, v in enumerate(values):
    ax1.text(i, v + 0.5, f'{v:.2f}s', ha='center', va='bottom')

# Panel 2: Waiting Time Statistics
values = [
    data['TempoMédioEspera'].mean(),
    data['TempoMédioEspera'].min(),
    data['TempoMédioEspera'].max(),
    data['TempoMédioEspera'].std()
]
ax2.bar(metrics, values, color=[color, 'lightblue', 'darkblue', 'gray'])
ax2.set_title('Estatísticas de Tempo de Espera')
ax2.set_ylabel('Tempo (s)')
ax2.grid(axis='y', alpha=0.3)
for i, v in enumerate(values):
    ax2.text(i, v + 0.5, f'{v:.2f}s', ha='center', va='bottom')

# Panel 3: Completion Rate Distribution
ax3.hist(data['TaxaConclusão'], bins=10, color=color, alpha=0.7, edgecolor='black')
ax3.axvline(data['TaxaConclusão'].mean(), color='red', linestyle='--', linewidth=2, label='Média')
ax3.set_title('Distribuição da Taxa de Conclusão')
ax3.set_xlabel('Taxa de Conclusão (%)')
ax3.set_ylabel('Frequência')
ax3.legend()
ax3.grid(axis='y', alpha=0.3)

# Panel 4: Key Metrics Summary
summary_metrics = ['Veículos\nGerados', 'Veículos\nConcluídos', 'Taxa de\nConclusão (%)']
summary_values = [
    data['VeículosGerados'].mean(),
    data['VeículosCompletados'].mean(),
    data['TaxaConclusão'].mean()
]
# Create bars individually with different alpha values
alphas = [0.5, 0.7, 0.9]
for i, (metric, value, alpha_val) in enumerate(zip(summary_metrics, summary_values, alphas)):
    ax4.bar(i, value, color=color, alpha=alpha_val)
ax4.set_xticks(range(len(summary_metrics)))
ax4.set_xticklabels(summary_metrics)
ax4.set_title('Resumo de Métricas-Chave')
ax4.grid(axis='y', alpha=0.3)
for i, v in enumerate(summary_values):
    ax4.text(i, v + max(summary_values)*0.02, f'{v:.1f}', ha='center', va='bottom', fontweight='bold')

plt.tight_layout()
plt.savefig(f'graphs/{load_type.lower()}_summary_statistics.png', dpi=300, bbox_inches='tight')
print(f"Graph saved: graphs/{load_type.lower()}_summary_statistics.png")
plt.close()

# Print detailed summary statistics
print("\n" + "="*60)
print(f"{load_name.upper()} LOAD - DETAILED STATISTICS")
print("="*60)

print(f"\nTIME IN SYSTEM:")
print(f"  Mean: {data['TempoMédioSistema'].mean():.2f}s")
print(f"  Std Dev: {data['TempoMédioSistema'].std():.2f}s")
print(f"  Min: {data['TempoMínimoSistema'].min():.2f}s")
print(f"  Max: {data['TempoMáximoSistema'].max():.2f}s")
print(f"  Median: {data['TempoMédioSistema'].median():.2f}s")

print(f"\nWAITING TIME:")
print(f"  Mean: {data['TempoMédioEspera'].mean():.2f}s")
print(f"  Std Dev: {data['TempoMédioEspera'].std():.2f}s")
print(f"  Min: {data['TempoMédioEspera'].min():.2f}s")
print(f"  Max: {data['TempoMédioEspera'].max():.2f}s")
print(f"  Median: {data['TempoMédioEspera'].median():.2f}s")

print(f"\nCOMPLETION RATE:")
print(f"  Mean: {data['TaxaConclusão'].mean():.2f}%")
print(f"  Std Dev: {data['TaxaConclusão'].std():.2f}%")
print(f"  Min: {data['TaxaConclusão'].min():.2f}%")
print(f"  Max: {data['TaxaConclusão'].max():.2f}%")
print(f"  Median: {data['TaxaConclusão'].median():.2f}%")

print(f"\nVEHICLE COUNTS:")
print(f"  Mean Generated: {data['VeículosGerados'].mean():.0f}")
print(f"  Mean Completed: {data['VeículosCompletados'].mean():.0f}")
print(f"  Mean Lost: {data['VeículosGerados'].mean() - data['VeículosCompletados'].mean():.0f}")

print(f"\nRUNS ANALYZED: {len(data)}")

# Check for config file column - could be ArquivoConfig or ConfigFile
config_col = None
if 'ArquivoConfig' in data.columns:
    config_col = 'ArquivoConfig'
elif 'ConfigFile' in data.columns:
    config_col = 'ConfigFile'

if config_col:
    print(f"CONFIGURATION FILE: {data[config_col].iloc[0]}")
else:
    print(f"CONFIGURATION FILE: N/A")

print("\n" + "="*60)
print(f"All graphs saved in 'graphs/' directory with prefix '{load_type.lower()}_'")
print("="*60)
