"""Sample tests for PA2 Part B (word_utils)."""

from colorama import Fore, Style
from file_utils import Grid
from pytest import raises

from word_utils import (
    is_solved,
    check_swap,
    cell_to_str,
    print_grid,
    update_grid,
    swap_cells,
)


def make_grid(letter: str = "A", color: str = "GREEN") -> Grid:
    """Create a valid grid of 25 cells for testing.

    Args:
        letter: The letter to put in every cell.
        color: The color to put in every cell.

    Returns:
        The generated grid.
    """
    return [[letter, color] for _ in range(25)]


def test_is_solved():
    grid1 = make_grid("A")
    grid2 = make_grid("B")
    assert is_solved(grid1, grid1)
    assert not is_solved(grid1, grid2)


def test_check_swap():
    assert check_swap("a", "b") == "valid"
    assert check_swap("a", "z") == "out of range"


def test_cell_to_str():
    assert cell_to_str(["A", "GREEN"]) == Fore.GREEN + "[A]" + Style.RESET_ALL
    assert cell_to_str(["B", "RED"]) == Fore.RED + "_B_" + Style.RESET_ALL


def test_print_grid(capsys):
    grid = make_grid("A")
    print_grid(grid)
    captured = capsys.readouterr()
    row = (Fore.GREEN + "[A]" + Style.RESET_ALL + " ") * 5
    assert captured.out == (
          row + "   a b c d e\n"
        + row + "   f   h   j\n"
        + row + "   k l m n o\n"
        + row + "   p   r   t\n"
        + row + "   u v w x y\n"
    )


def test_update_grid():
    grid1 = make_grid("A")
    grid2 = make_grid("B")
    grid2[0][0] = "A"
    result = update_grid(grid1, grid2)
    assert result[0][1] == "GREEN"
    assert result[1][1] == "RED"


def test_swap_cells():
    grid = make_grid("A")
    grid[0][0] = "X"
    grid[1][0] = "Y"

    # Test a valid swap
    swapped = swap_cells("a", "b", grid)
    assert swapped[0][0] == "Y"
    assert swapped[1][0] == "X"

    # Test an invalid swap
    with raises(ValueError, match="out of range"):
        swap_cells("a", "g", grid)
