#!/usr/bin/env python3
import os
import csv
import json

# Collect data from all languages
data = {}
languages = []

# Read data from each language
for lang in os.listdir('data'):
    lang_dir = os.path.join('data', lang)
    if os.path.isdir(lang_dir):
        summary_file = os.path.join(lang_dir, 'summary.csv')
        if os.path.exists(summary_file):
            languages.append(lang)
            with open(summary_file, 'r') as f:
                reader = csv.DictReader(f)
                lang_data = {}
                for row in reader:
                    lang_data[row['metric']] = float(row['value'])
                data[lang] = lang_data

# Sort by time
sorted_by_time = sorted(languages, key=lambda x: data[x].get('time_ms', float('inf')))

# Print analysis
print("\n=== Top 10 snabbaste språk ===")
for i, lang in enumerate(sorted_by_time[:10], 1):
    d = data[lang]
    print(f"{i}. {lang:15} {d['time_ms']:6.0f} ms, {d['memory_bytes']:10.0f} bytes, IPC: {d['ipc']:.2f}")

print("\n=== Top 10 minneseffektiva språk ===")
sorted_by_memory = sorted(languages, key=lambda x: data[x].get('memory_bytes', float('inf')))
for i, lang in enumerate(sorted_by_memory[:10], 1):
    d = data[lang]
    print(f"{i}. {lang:15} {d['memory_bytes']:10.0f} bytes, {d['time_ms']:6.0f} ms, IPC: {d['ipc']:.2f}")

print("\n=== Top 10 högsta IPC (effektivitet) ===")
sorted_by_ipc = sorted(languages, key=lambda x: data[x].get('ipc', 0), reverse=True)
for i, lang in enumerate(sorted_by_ipc[:10], 1):
    d = data[lang]
    print(f"{i}. {lang:15} IPC: {d['ipc']:.2f}, {d['time_ms']:6.0f} ms")

# Save data for visualization
with open('data/analysis.json', 'w') as f:
    json.dump(data, f, indent=2)

print("\n=== Data sparad till data/analysis.json ===")