from collections import deque
from dataclasses import dataclass
from typing import Tuple, Optional

import numpy as np
from termcolor import colored


GRID_SIDE_LENGTH = 11
EXCEED_BOUNDS_BY_UP_TO = 0
COLORS = ["red", "blue", "green", "yellow"]
SHAPES = [
    [
        [0, 1, 1, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 0, 0, 0, 0, 0],
    ],
    [
        [1, 1, 0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 1, 1, 0, 0],
        [1, 0, 0, 0, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
    ],
    [
        [1, 1, 1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0],
        [0, 1, 1, 1, 0, 0, 0, 0],
    ],
    [
        [1, 1, 1, 1, 1, 0, 0, 0],
        [1, 0, 0, 0, 1, 1, 1, 0],
        [1, 0, 0, 0, 1, 0, 0, 0],
        [1, 0, 0, 0, 1, 0, 0, 0],
        [0, 0, 0, 0, 1, 0, 0, 0],
        [0, 0, 1, 1, 1, 0, 0, 0],
        [0, 0, 1, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0, 0, 0, 0],
    ],
]


@dataclass
class PieceState:
    """Class for keeping track of the position of one piece"""

    x: Optional[int]
    y: Optional[int]
    flipped: bool
    rotation: int

    def __hash__(self):
        return hash((self.x, self.y, self.flipped, self.rotation))


def all_piece_placements():
    for rotation in range(4):
        for flipped in [True, False]:
            for x in range(
                -EXCEED_BOUNDS_BY_UP_TO, GRID_SIDE_LENGTH + EXCEED_BOUNDS_BY_UP_TO + 1
            ):
                for y in range(
                    -EXCEED_BOUNDS_BY_UP_TO,
                    GRID_SIDE_LENGTH + EXCEED_BOUNDS_BY_UP_TO + 1,
                ):
                    yield PieceState(x, y, flipped, rotation)


@dataclass
class BoardState:
    pieces: Tuple[PieceState]

    def __hash__(self):
        return hash(self.pieces)

    def print(self):
        grid = np.zeros((GRID_SIDE_LENGTH, GRID_SIDE_LENGTH))
        for (p, piece) in enumerate(self.pieces):
            if piece.x is None or piece.y is None:
                continue
            shape = np.array(SHAPES[p])
            if piece.flipped:
                shape = np.flip(shape, 0)
            shape = np.rot90(shape, piece.rotation)
            for y_ctr in range(shape.shape[0]):
                for x_ctr in range(shape.shape[1]):
                    if shape[y_ctr, x_ctr] != 0:
                        if piece.y + y_ctr < 0 or piece.y + y_ctr >= grid.shape[0]:
                            continue
                        if piece.x + x_ctr < 0 or piece.x + x_ctr >= grid.shape[1]:
                            continue
                        grid[piece.y + y_ctr, piece.x + x_ctr] = shape[y_ctr, x_ctr] * (
                            p + 1
                        )

        for row in grid:
            for cell in row:
                if cell == 0:
                    print(colored("\u2588", "grey"), end="")
                else:
                    print(colored("\u2588", COLORS[int(cell - 1)]), end="")
            print()

    def is_valid(self):
        grid = np.zeros((GRID_SIDE_LENGTH, GRID_SIDE_LENGTH))
        for (p, piece) in enumerate(self.pieces):
            if piece.x is None or piece.y is None:
                continue
            shape = np.array(SHAPES[p])
            if piece.flipped:
                shape = np.flip(shape, 0)
            shape = np.rot90(shape, piece.rotation)
            for y_ctr in range(shape.shape[0]):
                for x_ctr in range(shape.shape[1]):
                    if shape[y_ctr, x_ctr] != 0:
                        if piece.y + y_ctr < 0 or piece.y + y_ctr >= grid.shape[0]:
                            return False
                        if piece.x + x_ctr < 0 or piece.x + x_ctr >= grid.shape[1]:
                            return False
                        grid[piece.y + y_ctr, piece.x + x_ctr] += shape[y_ctr, x_ctr]

        for row in grid:
            for cell in row:
                if cell > 1:
                    return False

        return True

    def all_pieces_placed(self):
        for piece in self.pieces:
            if piece.x is None or piece.y is None:
                return False
        return True

    def update(self, piece_to_place, piece_placement):
        pieces = ()
        for p in range(4):
            if p == piece_to_place:
                pieces = pieces + (piece_placement,)
            else:
                pieces = pieces + (self.pieces[p],)
        return BoardState(pieces)

    def neighbors(self):
        neighbors = list()
        piece_to_place = 0
        for piece in self.pieces:
            if piece.x is not None and piece.y is not None:
                piece_to_place += 1
        assert piece_to_place < len(self.pieces)
        for piece_placement in all_piece_placements():
            neighbor = self.update(piece_to_place, piece_placement)
            if neighbor.is_valid():
                neighbors.append(neighbor)
        return neighbors


def dfs(root):
    queue = deque([root])
    visited = set()
    visited.add(root)

    while queue:
        state = queue.pop()

        print()
        state.print()

        if state.all_pieces_placed():
            return

        for neighbor in state.neighbors():
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)


def main():
    pieces = tuple()
    for p in range(4):
        pieces = pieces + (PieceState(None, None, False, 0),)
    root = BoardState(pieces=pieces)

    dfs(root)


if __name__ == "__main__":
    main()
