from abc import ABC, abstractmethod
from maze_core import Maze, Cell

class MazeBuilder(ABC):
    @abstractmethod
    def load(self, filepath: str) -> Maze:
        pass

class TextMazeBuilder(MazeBuilder):
    def load(self, filepath: str) -> Maze:
        with open(filepath, 'r', encoding='utf-8') as f:
            lines = [line.rstrip() for line in f if line.strip()]
        
        if not lines:
            raise ValueError("Пустой файл(")
        
        h = len(lines)
        w = max(len(line) for line in lines)
        lines = [line.ljust(w) for line in lines]
        
        maze = Maze(w, h)
        
        for y, line in enumerate(lines):
            for x, ch in enumerate(line):
                cell = Cell(x, y)
                if ch == '#':
                    cell.is_wall = True
                elif ch == 'S':
                    cell.is_start = True
                    maze.start_cell = cell
                elif ch == 'E':
                    cell.is_exit = True
                    maze.exit_cell = cell
                maze.grid[y][x] = cell
        
        if not maze.start_cell or not maze.exit_cell:
            raise ValueError("Лабиринт должен иметь старт и выход")
        
        return maze