from source.build.builder import TextFileBuilder
from source.models.base import Maze
from source.view.observer import ConsoleView, Event
from source.view.command import Player, MoveCommand, CommandHistory


maze: Maze = TextFileBuilder().build_from_file("source/templates/10x10_path_v1.txt")

rows, cols = maze.shape

start = None
for y in range(rows):
    for x in range(cols):
        if maze[y, x].is_start:
            start = maze[y, x]
            break

if start is None:
    print("Стартовая клетка не найдена!")
    exit()

player = Player(start)
history = CommandHistory()
view = ConsoleView()

view.update(Event("maze_loaded", {"maze": maze}))
print("Управление: w/a/s/d — движение, z — отмена, q — выход\n")

while True:
    key = input(">>> ").strip().lower()

    if key == "q":
        print("Выход.")
        break

    elif key == "z":
        if history.undo():
            print("Ход отменён.")
            view.render(maze, player=player.cell)

    elif key in ("w", "a", "s", "d"):
        cmd = MoveCommand(player, key, maze)
        if cmd.execute():
            history.push(cmd)
            view.update(
                Event(
                    "move",
                    {
                        "maze": maze,
                        "player_cell": player.cell,
                        "direction": key,
                    },
                )
            )
            if player.cell.is_exit:
                print("Выход найден! Победа!")
                break
        else:
            print("Туда нельзя — стена или граница.")

    else:
        print("Неизвестная команда. Используй: w/a/s/d, z, q")
