
import csv
import os
import statistics

from maze_builder import TextFileMazeBuilder
from maze_solver import MazeSolver
from strategies import BFSStrategy, DFSStrategy, AStarStrategy, DijkstraStrategy

MAZES_DIR = "mazes"
OUTPUT_CSV = "results.csv"
RUNS = 7  # количество запусков для усреднения

STRATEGIES = {
    "BFS": BFSStrategy,
    "DFS": DFSStrategy,
    "A*": AStarStrategy,
    "Dijkstra": DijkstraStrategy,
}

builder = TextFileMazeBuilder()

maze_files = sorted(
    f for f in os.listdir(MAZES_DIR) if f.endswith(".txt")
)

rows = []

for maze_file in maze_files:
    maze_name = maze_file.replace(".txt", "")
    filepath = os.path.join(MAZES_DIR, maze_file)

    try:
        maze = builder.build_from_file(filepath)
    except ValueError as e:
        print(f"  [!] Пропуск {maze_file}: {e}")
        continue

    print(f"\n{'='*50}")
    print(f"Лабиринт: {maze_name}  ({maze.width}×{maze.height})")

    for strat_name, StratClass in STRATEGIES.items():
        times, visited_counts, path_lengths = [], [], []

        for _ in range(RUNS):
            solver = MazeSolver(maze, StratClass())
            stats = solver.solve()
            times.append(stats.time_ms)
            visited_counts.append(stats.visited_cells)
            path_lengths.append(stats.path_length)

        avg_time = statistics.mean(times)
        avg_visited = statistics.mean(visited_counts)
        avg_path = statistics.mean(path_lengths)

        print(f"  {strat_name:10s} | время: {avg_time:.4f} мс | "
              f"посещено: {avg_visited:.1f} | длина пути: {avg_path:.1f}")

        rows.append({
            "лабиринт": maze_name,
            "стратегия": strat_name,
            "время_мс": round(avg_time, 6),
            "посещено_клеток": round(avg_visited, 1),
            "длина_пути": round(avg_path, 1),
        })

# Сохраняем CSV
with open(OUTPUT_CSV, "w", newline="", encoding="utf-8") as csvfile:
    fieldnames = ["лабиринт", "стратегия", "время_мс", "посещено_клеток", "длина_пути"]
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)

print(f"\n✓ Результаты сохранены в {OUTPUT_CSV}")
