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

# 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)

# Carregar dados
print("Looking for analysis files...")
low = load_latest_csv('analysis/LOW_LOAD_*.csv')
medium = load_latest_csv('analysis/MEDIUM_LOAD_*.csv')
high = load_latest_csv('analysis/HIGH_LOAD_*.csv')

# Check if we have all data
if low is None or medium is None or high is None:
    print("\nError: Missing analysis files!")
    print("Please run the batch analysis first:")
    exit(1)

# Print available columns for debugging
print("\nAvailable columns in LOW_LOAD CSV:")
print(low.columns.tolist())

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

# 1. Gráfico: Dwelling Time vs Load
plt.figure(figsize=(10, 6))
dwelling_times = [
    low['TempoMédioSistema'].mean(),
    medium['TempoMédioSistema'].mean(),
    high['TempoMédioSistema'].mean()
]
plt.bar(['Baixa', 'Média', 'Alta'], dwelling_times, color=['green', 'orange', 'red'])
plt.ylabel('Tempo Médio no Sistema (s)')
plt.title('Desempenho do Sistema vs Carga')
plt.xlabel('Cenário de Carga')
plt.grid(axis='y', alpha=0.3)
for i, v in enumerate(dwelling_times):
    plt.text(i, v + 1, f'{v:.2f}s', ha='center', va='bottom')
plt.savefig('graphs/dwelling_time_comparison.png', dpi=300, bbox_inches='tight')
print("\nGraph saved: graphs/dwelling_time_comparison.png")
plt.close()

# 2. Gráfico: Completion Rate vs Load
plt.figure(figsize=(10, 6))
completion_rates = [
    low['TaxaConclusão'].mean(),
    medium['TaxaConclusão'].mean(),
    high['TaxaConclusão'].mean()
]
plt.bar(['Baixa', 'Média', 'Alta'], completion_rates, color=['green', 'orange', 'red'])
plt.ylabel('Taxa de Conclusão (%)')
plt.title('Taxa de Conclusão de Veículos vs Carga')
plt.xlabel('Cenário de Carga')
plt.grid(axis='y', alpha=0.3)
plt.ylim(0, 100)
for i, v in enumerate(completion_rates):
    plt.text(i, v + 2, f'{v:.1f}%', ha='center', va='bottom')
plt.savefig('graphs/completion_rate_comparison.png', dpi=300, bbox_inches='tight')
print("Graph saved: graphs/completion_rate_comparison.png")
plt.close()

# 3. Gráfico: Waiting Time vs Load
plt.figure(figsize=(10, 6))
waiting_times = [
    low['TempoMédioEspera'].mean(),
    medium['TempoMédioEspera'].mean(),
    high['TempoMédioEspera'].mean()
]
plt.bar(['Baixa', 'Média', 'Alta'], waiting_times, color=['green', 'orange', 'red'])
plt.ylabel('Tempo Médio de Espera (s)')
plt.title('Tempo Médio de Espera vs Carga')
plt.xlabel('Cenário de Carga')
plt.grid(axis='y', alpha=0.3)
for i, v in enumerate(waiting_times):
    plt.text(i, v + 1, f'{v:.2f}s', ha='center', va='bottom')
plt.savefig('graphs/waiting_time_comparison.png', dpi=300, bbox_inches='tight')
print("Graph saved: graphs/waiting_time_comparison.png")
plt.close()

# 4. Gráfico: Summary Statistics
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
loads = ['Baixa', 'Média', 'Alta']

# Vehicles generated
ax1.bar(loads, [low['VeículosGerados'].mean(), medium['VeículosGerados'].mean(), high['VeículosGerados'].mean()], color=['green', 'orange', 'red'])
ax1.set_title('Veículos Gerados')
ax1.set_ylabel('Quantidade')
ax1.grid(axis='y', alpha=0.3)

# Vehicles completed
ax2.bar(loads, [low['VeículosCompletados'].mean(), medium['VeículosCompletados'].mean(), high['VeículosCompletados'].mean()], color=['green', 'orange', 'red'])
ax2.set_title('Veículos Concluídos')
ax2.set_ylabel('Quantidade')
ax2.grid(axis='y', alpha=0.3)

# Min/Max dwelling time
x = range(3)
width = 0.35
ax3.bar([i - width/2 for i in x], [low['TempoMínimoSistema'].mean(), medium['TempoMínimoSistema'].mean(), high['TempoMínimoSistema'].mean()], width, label='Mín', color='lightblue')
ax3.bar([i + width/2 for i in x], [low['TempoMáximoSistema'].mean(), medium['TempoMáximoSistema'].mean(), high['TempoMáximoSistema'].mean()], width, label='Máx', color='darkblue')
ax3.set_title('Tempo no Sistema Mín/Máx')
ax3.set_ylabel('Tempo (s)')
ax3.set_xticks(x)
ax3.set_xticklabels(loads)
ax3.legend()
ax3.grid(axis='y', alpha=0.3)

# Performance summary
metrics = ['Tempo no\nSistema', 'Tempo de\nEspera', 'Taxa de\nConclusão']
low_vals = [low['TempoMédioSistema'].mean(), low['TempoMédioEspera'].mean(), low['TaxaConclusão'].mean()]
med_vals = [medium['TempoMédioSistema'].mean(), medium['TempoMédioEspera'].mean(), medium['TaxaConclusão'].mean()]
high_vals = [high['TempoMédioSistema'].mean(), high['TempoMédioEspera'].mean(), high['TaxaConclusão'].mean()]

x = range(len(metrics))
width = 0.25
ax4.bar([i - width for i in x], low_vals, width, label='Baixa', color='green')
ax4.bar(x, med_vals, width, label='Média', color='orange')
ax4.bar([i + width for i in x], high_vals, width, label='Alta', color='red')
ax4.set_title('Resumo de Desempenho')
ax4.set_xticks(x)
ax4.set_xticklabels(metrics)
ax4.legend()
ax4.grid(axis='y', alpha=0.3)

plt.tight_layout()
plt.savefig('graphs/summary_statistics.png', dpi=300, bbox_inches='tight')
print("Graph saved: graphs/summary_statistics.png")
plt.close()

# Print summary statistics
print("\n" + "="*60)
print("SUMMARY STATISTICS")
print("="*60)
print(f"\nLOW LOAD:")
print(f"  Avg Dwelling Time: {low['TempoMédioSistema'].mean():.2f}s")
print(f"  Avg Waiting Time: {low['TempoMédioEspera'].mean():.2f}s")
print(f"  Completion Rate: {low['TaxaConclusão'].mean():.1f}%")
print(f"  Vehicles Generated: {low['VeículosGerados'].mean():.0f}")
print(f"  Vehicles Completed: {low['VeículosCompletados'].mean():.0f}")

print(f"\nMEDIUM LOAD:")
print(f"  Avg Dwelling Time: {medium['TempoMédioSistema'].mean():.2f}s")
print(f"  Avg Waiting Time: {medium['TempoMédioEspera'].mean():.2f}s")
print(f"  Completion Rate: {medium['TaxaConclusão'].mean():.1f}%")
print(f"  Vehicles Generated: {medium['VeículosGerados'].mean():.0f}")
print(f"  Vehicles Completed: {medium['VeículosCompletados'].mean():.0f}")

print(f"\nHIGH LOAD:")
print(f"  Avg Dwelling Time: {high['TempoMédioSistema'].mean():.2f}s")
print(f"  Avg Waiting Time: {high['TempoMédioEspera'].mean():.2f}s")
print(f"  Completion Rate: {high['TaxaConclusão'].mean():.1f}%")
print(f"  Vehicles Generated: {high['VeículosGerados'].mean():.0f}")
print(f"  Vehicles Completed: {high['VeículosCompletados'].mean():.0f}")

print("\n" + "="*60)
print("All graphs saved in 'graphs/' directory!")
print("="*60)