from collections import deque
from typing import Optional

from source.models.base import Cell, Maze
from source.strategy.algorithms import PathFindingStrategy


class BFSStrategy(PathFindingStrategy):
    """Поиск в ширину (Breadth-First Search).

    Гарантирует кратчайший путь по количеству шагов.
    Сложность: O(V + E) по времени и памяти.
    """

    def find_path(
        self, maze: Maze, start: Optional[Cell] = None, exit: Optional[Cell] = None
    ) -> list[Cell]:
        start, exit = self._validate(maze, start, exit)

        came_from: dict[Cell, Optional[Cell]] = {start: None}
        queue: deque[Cell] = deque([start])

        while queue:
            current = queue.popleft()

            if current is exit:
                return self._reconstruct_path(came_from, exit)

            for neighbor in maze.get_neighbors(current.x, current.y):
                if neighbor not in came_from:
                    came_from[neighbor] = current
                    queue.append(neighbor)

        return []
