import os
import csv
from time import perf_counter

from src.builder.text_file_maze_builder import TextFileMazeBuilder
from src.strategy.bfs_strategy import BFSStrategy
from src.strategy.dfs_strategy import DFSStrategy
from src.strategy.astar_strategy import AStarStrategy
from src.solver.maze_solver import MazeSolver


def run_experiments():
    builder = TextFileMazeBuilder()

    strategies = {
        "BFS": BFSStrategy(),
        "DFS": DFSStrategy(),
        "A*": AStarStrategy()
    }

    maze_dir = "../mazes"
    files = [f for f in os.listdir(maze_dir) if f.endswith(".txt")]

    results = []

    for maze_file in files:
        maze_path = os.path.join(maze_dir, maze_file)
        maze = builder.build_from_file(maze_path)

        for name, strategy in strategies.items():
            solver = MazeSolver(maze, strategy)

            t0 = perf_counter()
            stats = solver.solve()
            t1 = perf_counter()

            results.append([
                maze_file,
                name,
                stats.time_ms,
                stats.visited,
                stats.path_len
            ])

            print(f"{maze_file} | {name} | {stats}")

    # save CSV
    with open("results.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["maze", "algorithm", "time_ms", "visited", "path_len"])
        writer.writerows(results)


if __name__ == "__main__":
    run_experiments()
