import csv

from builder import TextFileMazeBuilder
from strategies import BFSStrategy, DFSStrategy, AStarStrategy
from solver import MazeSolver
from observer import ConsoleView


def print_path(maze, path):
    path_coords = {(cell.x, cell.y) for cell in path}

    for row in maze.cells:
        line = ""

        for cell in row:
            if cell.is_wall:
                line += "#"
            elif cell.is_start:
                line += "S"
            elif cell.is_exit:
                line += "E"
            elif (cell.x, cell.y) in path_coords:
                line += "*"
            else:
                line += " "

        print(line)


builder = TextFileMazeBuilder()

maze_files = [
    "docs/task2/mazes/small.txt",
    "docs/task2/mazes/medium.txt",
    "docs/task2/mazes/blocked.txt",
    "docs/task2/mazes/large.txt",
    "docs/task2/mazes/empty.txt",
    "docs/task2/mazes/no_exit.txt"
]

strategies = [
    BFSStrategy(),
    DFSStrategy(),
    AStarStrategy()
]

results = []

for maze_file in maze_files:
    print("\n======================")
    print("Maze:", maze_file)

    try:
        maze = builder.build_from_file(maze_file)

    except Exception as e:
        print("Error:", e)
        continue

    for strategy in strategies:
        print("\nStrategy:", strategy.__class__.__name__)

        solver = MazeSolver(maze, strategy)

        observer = ConsoleView()
        solver.add_observer(observer)

        runs = 5
        total_time = 0
        last_stats = None
        last_path = []

        for _ in range(runs):
            stats, path = solver.solve()

            total_time += stats.time_ms
            last_stats = stats
            last_path = path

        average_time = total_time / runs

        print("Average time ms:", round(average_time, 4))
        print("Visited:", last_stats.visited_cells)
        print("Path length:", last_stats.path_length)

        if last_path:
            print_path(maze, last_path)
        else:
            print("Path not found")

        results.append([
            maze_file,
            strategy.__class__.__name__,
            round(average_time, 4),
            last_stats.visited_cells,
            last_stats.path_length
        ])

with open("maze_results.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)

    writer.writerow([
        "maze",
        "strategy",
        "time_ms",
        "visited_cells",
        "path_length"
    ])

    writer.writerows(results)

print("\nResults saved to maze_results.csv")