"""
Utility for unit testing Connect4 library submissions.

To use this:
(1) Save this file to the same location as the module (library) file to test.
(2) Run this program. It finds your library file automatically.

Author: Steve Willis
Version: 1.3
"""

### DO NOT EDIT THIS FILE! ###

from contextlib import redirect_stdout, redirect_stderr
import copy
import importlib
import inspect
import os
import random
import sys

ROWS = 6
COLS = 7

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

MODULE_NAME = None  # set automatically by find_module_name()

def find_module_name():
    """Find the library to test: the only other .py file in this folder."""
    this_file = os.path.basename(__file__)
    candidates = [f[:-3] for f in sorted(os.listdir(HERE))
                  if f.endswith(".py") and f != this_file]
    if len(candidates) == 1:
        return candidates[0]
    if len(candidates) == 0:
        print("No library found to test!")
        print(f"Save your Connect4 .py file in this folder: {HERE}")
        return None
    print("More than one .py file is in this folder. Which is your library?")
    for i, name in enumerate(candidates):
        print(f"  ({i}) {name}.py")
    while True:
        choice = input("Enter a number: ")
        if choice.isdigit() and int(choice) < len(candidates):
            return candidates[int(choice)]

def empty_state():
    """Helper function to generate an empty game board."""
    return [["-" for j in range(COLS)] for i in range(ROWS)]

def tied_state():
    """Helper function to generate a tied game board."""
    row_a = list("RRRYRRR")
    row_b = list("YYYRYYY")
    return [row[:] for row in (row_a, row_b) * 3]

def rand_state():
    """Helper function to generate a random, reachable state with no winner."""
    def check_winner():
        directions = ((0, 1), (1, 0), (1, 1), (1, -1))
        for r in range(ROWS):
            for c in range(COLS):
                p = state[r][c]
                if p not in ("R", "Y"):
                    continue
                for dr, dc in directions:
                    er, ec = r + 3 * dr, c + 3 * dc
                    if 0 <= er < ROWS and 0 <= ec < COLS:
                        if all(state[r + i * dr][c + i * dc] == p for i in range(4)):
                            return True
        return None

    state = empty_state()
    player = "R"
    moves = random.randint(0, ROWS * COLS - 1)  # number of moves to make
    heights = [0] * COLS  # how many pieces currently in each column (0..6)
    for _ in range(moves):
        legal_cols = [c for c in range(COLS) if heights[c] < ROWS]
        if not legal_cols:
            break

        c = random.choice(legal_cols)
        r = ROWS - 1 - heights[c]
        state[r][c] = player
        heights[c] += 1

        while check_winner():
            # take back the last (winning) move
            state[r][c] = "-"
            heights[c] -= 1
            legal_cols.remove(c)

            if len(legal_cols) > 0:
                c = random.choice(legal_cols)
                r = ROWS - 1 - heights[c]
                state[r][c] = player
                heights[c] += 1
            else:
                return state, player

        player = "Y" if player == "R" else "R"

    return state, player

def test_01_import():
    """The library imports without error"""
    if not os.path.exists(os.path.join(HERE, f"{MODULE_NAME}.py")):
        return f"{MODULE_NAME}.py does not exist"
    importlib.import_module(MODULE_NAME)
    return None

def test_02_has_required_functions():
    """The library contains all required functions with correct spelling"""
    required = {
        "get_name": (),
        "check_move": ("piece", "column", "state"),
        "check_win": ("state",),
        "make_move": ("piece", "state"),
    }
    module = importlib.import_module(MODULE_NAME)
    for name, names in required.items():
        fn = getattr(module, name, None)
        if not inspect.isfunction(fn):
            return f"missing function {name}"
        params = list(inspect.signature(fn).parameters.values())
        if tuple(p.name for p in params) != names or any(
            p.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD for p in params
        ):
            return f"expected {name}({', '.join(names)})"
    return None

def test_03_get_name():
    """get_name() returns a string with nonzero length"""
    module = importlib.import_module(MODULE_NAME)
    result = module.get_name()
    err = None
    if not isinstance(result, str):
        err = "did not return a string"
    elif len(result) < 1:
        err = "returned string is zero length"
    return err

def test_04_check_move_input():
    """check_move() accepts either a R or Y piece"""
    module = importlib.import_module(MODULE_NAME)
    r = module.check_move("R", 0, empty_state())
    y = module.check_move("Y", 0, empty_state())
    return "expected True for both piece types" if r is not True or y is not True else None

def test_05_check_move_bounds():
    """check_move() rejects nonexistent columns"""
    module = importlib.import_module(MODULE_NAME)
    result_low = module.check_move("R", -1, empty_state())
    result_high = module.check_move("R", COLS, empty_state())
    err = None
    if not isinstance(result_low, bool) or not isinstance(result_high, bool):
        err = "wrong type returned"
    elif result_low or result_high:
        err = "allowed nonexistent column(s)"
    return err

def test_06_check_move_empty():
    """check_move() accepts available columns and enforces piece-count balance"""
    module = importlib.import_module(MODULE_NAME)
    err = None

    # create a state with all but the top row filled with no winning combos
    state = [
        ["-", "-", "-", "-", "-", "-", "-"],
        ["R", "Y", "R", "Y", "R", "Y", "R"],
        ["Y", "R", "Y", "R", "Y", "R", "Y"],
        ["Y", "R", "Y", "R", "Y", "R", "Y"],
        ["R", "Y", "R", "Y", "R", "Y", "R"],
        ["R", "Y", "R", "Y", "R", "Y", "R"],
    ]

    # it is yellow's turn based on piece counts
    results = [module.check_move("Y", c, copy.deepcopy(state)) for c in range(COLS)]
    if not all(isinstance(r, bool) for r in results):
        err = "wrong type returned (expected True or False)"
    elif not all(results):
        err = "one or more partially-filled columns was not accepted"
    if err:
        return err
    for piece in ("R", "Y"):
        state = empty_state()
        state[-1][0] = piece
        other = "Y" if piece == "R" else "R"
        if module.check_move(piece, 1, copy.deepcopy(state)) is not False:
            return f"allowed {piece} to move twice in a row"
        if module.check_move(other, 1, copy.deepcopy(state)) is not True:
            return f"rejected {other}'s legal reply"
    return err

def test_07_check_move_full():
    """check_move() rejects moves in full columns"""
    module = importlib.import_module(MODULE_NAME)
    err = None
    results = [module.check_move("R", c, tied_state()) for c in range(COLS)]
    if not all([isinstance(r, bool) for r in results]):
        err = "wrong type returned"
    elif any(results):
        err = "move allowed with full board"
    if err:
        return err
    for c in range(COLS):
        state = empty_state()
        for r in range(ROWS):
            state[r][c] = "R" if r % 2 else "Y"
        for piece in ("R", "Y"):
            if module.check_move(piece, c, copy.deepcopy(state)) is not False:
                return f"allowed a move into full column {c}"
    return err

def test_08_test_check_win_in_progress_empty():
    """check_win() detects a game is in progress (tested with empty board)."""
    module = importlib.import_module(MODULE_NAME)
    result = module.check_win(empty_state())

    if not isinstance(result, str):
        return "wrong type returned"
    if result not in ("WIN", "TIE", "IN PROGRESS"):
        return f"invalid response {result} (not WIN/TIE/IN PROGRESS)"
    if result != "IN PROGRESS":
        return f"incorrect response {result} (expected IN PROGRESS)"
    return None

def test_09_test_check_win_in_progress():
    """check_win() detects a game is in progress (tested with 1 - 41 pieces)."""
    module = importlib.import_module(MODULE_NAME)
    tied = tied_state()
    state = empty_state()

    # copy one piece at a time from the tied state to an initially empty state
    # from the bottom up.
    i = 0
    for r in reversed(range(ROWS)):
        for c in range(COLS):
            i += 1
            if i == 42: # don't test a 42nd piece...would be a tie
                return None

            state[r][c] = tied[r][c]
            result = module.check_win(state)

            if not isinstance(result, str):
                return "wrong type returned"
            if result not in ("WIN", "TIE", "IN PROGRESS"):
                return f"invalid response {result} (not WIN/TIE/IN PROGRESS)"
            if result != "IN PROGRESS":
                return f"incorrect response {result} (expected IN PROGRESS)"

def check_winning_lines(directions):
    module = importlib.import_module(MODULE_NAME)
    for piece in ("R", "Y"):
        for dr, dc in directions:
            for r in range(ROWS):
                for c in range(COLS):
                    if not (0 <= r + 3 * dr < ROWS and 0 <= c + 3 * dc < COLS):
                        continue
                    state = empty_state()
                    for i in range(4):
                        state[r + i * dr][c + i * dc] = piece
                    result = module.check_win(state)
                    if result != "WIN":
                        return (f"expected WIN, got {result!r}: {piece} line "
                                f"from ({r}, {c}) in direction ({dr}, {dc})")
    return None


def test_10_test_check_win_horiz():
    """check_win() detects all 24 horizontal lines for both colors"""
    return check_winning_lines(((0, 1),))


def test_11_test_check_win_vert():
    """check_win() detects all 21 vertical lines for both colors"""
    return check_winning_lines(((1, 0),))


def test_12_test_check_win_diag():
    """check_win() detects all 24 diagonal lines for both colors"""
    return check_winning_lines(((1, 1), (1, -1)))

def test_13_check_win_tie():
    """check_win() detects a tie and gives wins priority on full boards"""
    module = importlib.import_module(MODULE_NAME)
    result = module.check_win(tied_state())
    if not isinstance(result, str):
        return "wrong type returned"
    if result not in ("WIN", "TIE", "IN PROGRESS"):
        return f"invalid response {result} (not WIN/TIE/IN PROGRESS)"
    elif result != "TIE":
        return f"incorrect response ({result}, expected TIE)"
    state = tied_state()
    state[0][3], state[1][3] = state[1][3], state[0][3]
    result = module.check_win(state)
    if result != "WIN":
        return f"expected WIN on a full board with a winning line, got {result!r}"
    return None

def test_14_make_move_operation():
    """make_move() makes legal moves for 10,000 randomly-generated nonterminal boards"""
    n_tests = 10000
    module = importlib.import_module(MODULE_NAME)
    count = 0
    for _ in range(n_tests):
        state, piece = rand_state()
        result = module.make_move(piece, copy.deepcopy(state))
        if type(result) is not int:
            return f"wrong type returned after {count:,} legal moves"
        if 0 <= result < COLS and state[0][result] == "-":
            count += 1  # the move is legal
    if count != n_tests:
        return f"made {count:,} / {n_tests:,} legal moves"
    else:
        return None

def main():
    global MODULE_NAME
    MODULE_NAME = find_module_name()
    if MODULE_NAME is None:
        return

    random.seed(0)
    print()
    print(f"Testing {MODULE_NAME}.py")
    print()
    print("HOW TO USE THIS TOOL")
    print("====================")
    print("Address any FAIL or ERROR results below from TOP TO BOTTOM!")
    print("A failure on an earlier test can cause failures on later tests.")
    print()

    current_module = sys.modules[__name__]
    fns = sorted(inspect.getmembers(current_module, inspect.isfunction))
    fns = [fn for name, fn in fns if name.startswith("test")]
    for test in fns:
        try:
            with open(os.devnull, "w") as sink, redirect_stdout(sink), redirect_stderr(sink):
                err = test()
        except (Exception, SystemExit) as exc:
            err = f"{type(exc).__name__}: {exc}"
            result = "ERROR"
        else:
            result = "PASS" if err is None else "FAIL"
        print(f"{result}: {test.__doc__}")
        if err:
            print(f"\t{err}")
    print()
    print("End of tests.")

if __name__ == "__main__":
    main()
