import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from builders.text_file_maze_builder import TextFileMazeBuilder
from strategies.bfs_strategy import BFSStrategy
from strategies.dfs_strategy import DFSStrategy
from strategies.astar_strategy import AStarStrategy
from solver.maze_solver import MazeSolver

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MAZES_DIR = os.path.join(PROJECT_ROOT, "mazes")

mazes = ["small.txt", "medium.txt", "large.txt", "no_exit.txt", "empty.txt"]
strategies = [BFSStrategy(), DFSStrategy(), AStarStrategy()]
results = []
builder = TextFileMazeBuilder()

for maze_file in mazes:
    try:
        maze_path = os.path.join(MAZES_DIR, maze_file)
        maze = builder.build_from_file(maze_path)

        for strategy in strategies:
            solver = MazeSolver(maze, strategy)
            stats = solver.solve(maze_file)
            results.append(stats)
    except ValueError as e:
        print(f"Error with {maze_file}: {e}")
    except FileNotFoundError as e:
        print(f"File not found: {e}")

os.makedirs(os.path.join(PROJECT_ROOT, "experiments"), exist_ok=True)

results_path = os.path.join(PROJECT_ROOT, "experiments", "results.csv")
with open(results_path, "w") as file:
    file.write("maze,strategy,time_ms,visited_cells,path_length\n")
    for stat in results:
        file.write(stat.to_csv_row())

print(f"Saved {len(results)} results to {results_path}")