from builders.maze_builder import MazeBuilder
from models.cell import Cell
from models.maze import Maze


class TextFileMazeBuilder(MazeBuilder):

    def create_cell(self, symbol, x, y):

        if symbol == "#":
            return Cell(x, y, is_wall=True)

        if symbol == "S":
            return Cell(x, y, is_start=True)

        if symbol == "E":
            return Cell(x, y, is_exit=True)

        if symbol == " ":
            return Cell(x, y)

        raise ValueError(f"Unknown symbol: {symbol}")

    def build_from_file(self, filename):

        with open(filename, "r", encoding="utf-8") as file:
            rows = [line.rstrip("\n") for line in file]

        if not rows:
            raise ValueError("File is empty")

        width = len(rows[0])

        for row in rows:
            if len(row) != width:
                raise ValueError("Maze rows must have same length")

        cells = []

        start_cell = None
        exit_cell = None

        for y, row in enumerate(rows):

            current_row = []

            for x, symbol in enumerate(row):

                cell = self.create_cell(symbol, x, y)

                if cell.is_start:
                    start_cell = cell

                if cell.is_exit:
                    exit_cell = cell

                current_row.append(cell)

            cells.append(current_row)

        if start_cell is None:
            raise ValueError("Start not found")

        if exit_cell is None:
            raise ValueError("Exit not found")

        return Maze(cells, start_cell, exit_cell)