import csv
import matplotlib.pyplot as plt
import os

def plot_results():
    # Определяем правильный путь к results.csv
    script_dir = os.path.dirname(os.path.abspath(__file__))
    csv_path = os.path.join(script_dir, "results.csv")
    
    results = []
    with open(csv_path, "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            row['time_ms'] = float(row['time_ms'])
            row['visited'] = int(row['visited'])
            row['path_len'] = int(row['path_len'])
            results.append(row)

    mazes = sorted(set(r['maze'] for r in results))
    algorithms = sorted(set(r['algorithm'] for r in results))

    x_labels = []
    for m in mazes:
        for a in algorithms:
            x_labels.append(f"{m.replace('.txt','')}\n{a}")

    # График 1: Время выполнения
    plt.figure(figsize=(12, 6))
    times = []
    for m in mazes:
        for a in algorithms:
            val = [r['time_ms'] for r in results if r['maze'] == m and r['algorithm'] == a]
            times.append(val[0] if val else 0)
    plt.bar(x_labels, times)
    plt.ylabel("Время (мс)")
    plt.title("Сравнение времени выполнения алгоритмов")
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.savefig(os.path.join(script_dir, "plot_time.png"), dpi=150)
    plt.close()
    print("Сохранён: experiments/plot_time.png")

    # График 2: Посещённые клетки
    plt.figure(figsize=(12, 6))
    visited_list = []
    for m in mazes:
        for a in algorithms:
            val = [r['visited'] for r in results if r['maze'] == m and r['algorithm'] == a]
            visited_list.append(val[0] if val else 0)
    plt.bar(x_labels, visited_list)
    plt.ylabel("Посещено клеток")
    plt.title("Сравнение количества посещённых клеток")
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.savefig(os.path.join(script_dir, "plot_visited.png"), dpi=150)
    plt.close()
    print("Сохранён: experiments/plot_visited.png")

    # График 3: Длина пути
    plt.figure(figsize=(12, 6))
    path_list = []
    for m in mazes:
        for a in algorithms:
            val = [r['path_len'] for r in results if r['maze'] == m and r['algorithm'] == a]
            path_list.append(val[0] if val else 0)
    plt.bar(x_labels, path_list)
    plt.ylabel("Длина пути")
    plt.title("Сравнение длины найденного пути")
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.savefig(os.path.join(script_dir, "plot_path.png"), dpi=150)
    plt.close()
    print("Сохранён: experiments/plot_path.png")

if __name__ == "__main__":
    plot_results()