import time
from dataclasses import dataclass
from typing import List, Optional, Tuple
from models import Maze, Cell
from strategies import PathFindingStrategy


@dataclass
class SearchStats:
    
    time_ms: float
    visited_cells: int
    path_length: int
    
    def __str__(self) -> str:
        return (f"Время: {self.time_ms:.3f} мс, "
                f"Посещено клеток: {self.visited_cells}, "
                f"Длина пути: {self.path_length}")


class MazeSolver:
    
    def __init__(self, maze: Maze, strategy: Optional[PathFindingStrategy] = None):
        self._maze = maze
        self._strategy = strategy
    
    def set_strategy(self, strategy: PathFindingStrategy) -> None:
        self._strategy = strategy
    
    def solve(self) -> Tuple[List[Cell], SearchStats]:
        if self._strategy is None:
            raise ValueError("Стратегия не установлена")
        
        if self._maze.start is None or self._maze.exit is None:
            raise ValueError("Нет старта или выхода")
        
        start_time = time.perf_counter()
        path = self._strategy.find_path(self._maze, self._maze.start, self._maze.exit)
        end_time = time.perf_counter()
        
        time_ms = (end_time - start_time) * 1000
        
        stats = SearchStats(
            time_ms=time_ms,
            visited_cells=len(path),
            path_length=len(path)
        )
        
        return path, stats