import csv
import statistics
import matplotlib.pyplot as plt
import numpy as np
 
rows = []
with open("results.csv", encoding="utf-8") as f:
    for r in csv.DictReader(f):
        rows.append(r)
 
STRUCTS = ["LinkedList", "HashTable", "BST"]
MODE_MAP = {"shuffled": "случайный", "sorted": "отсортированный"}
OPS = [("insert", "Вставка"), ("find", "Поиск"), ("delete", "Удаление")]
 
def stats(structure, mode, operation):
    vals = [float(r["time_sec"]) for r in rows
            if r["structure"] == structure and r["mode"] == mode and r["operation"] == operation]
    if not vals:
        return 0.0, 0.0
    return statistics.mean(vals), statistics.stdev(vals) if len(vals) > 1 else 0.0
 
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
fig.suptitle("Среднее время операций (сек, лог-шкала, N=10 000, 5 повторений)")
 
x = np.arange(len(STRUCTS))
WIDTH = 0.35
 
for ax, (op_key, op_title) in zip(axes, OPS):
    for i, mode in enumerate(["shuffled", "sorted"]):
        avgs, stds = [], []
        for s in STRUCTS:
            avg, std = stats(s, mode, op_key)
            avgs.append(avg)
            stds.append(std)
        offset = (i - 0.5) * WIDTH
        ax.bar(x + offset, avgs, WIDTH, label=MODE_MAP[mode])
        ax.errorbar(x + offset, avgs, yerr=stds, fmt="none", capsize=4)
    ax.set_yscale("log")
    ax.set_title(op_title)
    ax.set_xticks(x)
    ax.set_xticklabels(STRUCTS)
    ax.set_ylabel("Время (сек)")
    ax.yaxis.grid(True, which="both", linestyle="--", alpha=0.5)
    ax.set_axisbelow(True)
    ax.legend()
 
plt.tight_layout()
plt.savefig("../../performance_comparison.png", dpi=150)
plt.show()