from model import Cell, Maze

class MazeBuilder:
    def buildFromFile(self, filename: str) -> Maze:
        raise NotImplementedError


class TextFileMazeBuilder(MazeBuilder):
    def buildFromFile(self, filename: str) -> Maze:
        with open(filename, "r", encoding="utf-8") as f:
            raw_lines = [line.rstrip("\n") for line in f if line.strip("\n") != ""]

        width = max(len(line) for line in raw_lines)
        grid = []

        start_count = 0
        exit_count = 0

        for y, line in enumerate(raw_lines):
            row = []
            padded = line.ljust(width)
            for x, ch in enumerate(padded):
                if ch == "#":
                    row.append(Cell(x, y, isWall=True))
                elif ch == "S":
                    row.append(Cell(x, y, isStart=True))
                    start_count += 1
                elif ch == "E":
                    row.append(Cell(x, y, isExit=True))
                    exit_count += 1
                elif ch == "1":
                    row.append(Cell(x, y, weight=1))
                elif ch == "2":
                    row.append(Cell(x, y, weight=2))
                elif ch == "3":
                    row.append(Cell(x, y, weight=3))
                else:
                    row.append(Cell(x, y))
            grid.append(row)

        maze = Maze(grid)

        if start_count != 1 or exit_count != 1:
            raise ValueError("В лабиринте должен быть ровно один S и один E")

        return maze