#!python
import sys
import time
import chess
import player

def color2str(color: chess.Color):
    return "WHITE" if color is chess.WHITE else "BLACK"

def play(white: player.PlayerInterface, black: player.PlayerInterface):
    """
    Déroulement d'une partie d'échecs au hasard des coups possibles. Cela va donner presque exclusivement
    des parties très longues et sans gagnant. Cela illustre cependant comment on peut jouer avec la librairie
    très simplement.
    """
    def step(board: chess.Board, current: player.PlayerInterface, opponent: player.PlayerInterface):
        move = current.getPlayerMove()
        assert move is not chess.Move.null()
        board.push(move)
        opponent.playOpponentMove(move)

        return move

    board = chess.Board()
    white.newGame(chess.WHITE)
    black.newGame(chess.BLACK)
    whiteTime = 0
    blackTime = 0

    i = 1
    while not board.is_game_over():
        try:
            st = time.time()
            if board.turn == chess.WHITE:
                move = step(board, white, black)
                nd = time.time()
                whiteTime += (nd - st)
            else:
                move = step(board, black, white)
                nd = time.time()
                blackTime += (nd - st)
        except:
            print(board)
            print(f"{color2str(board.turn)} cheated, end the game")
            print(sys.exception())
            break;

        print("----------------")
        print(board)
        print(f"Move {move}")
        print(f"Turn {i}")
        print(f"Time consumed : {nd - st:.5}")
        i += 1

    print(board.outcome())
    print(f"White time : {whiteTime:.5}")
    print(f"Black time : {blackTime:.5}")

    return board

def enumerate_moves(board: chess.Board, depth=1):
    if depth == 0:
        return []
    boards = []

    for move in board.generate_legal_moves():
        board.push(move)

        boards.append(board)
        boards += enumerate_moves(board, depth - 1)

        board.pop()

    return boards


def t_enum(board, depth):
    st = time.time()
    n = len(enumerate_moves(board, depth=depth))
    nd = time.time()
    print(f"{nd-st:.6f} {n}")


if __name__ == "__main__":
    black = player.RandomPlayer()
    white = player.AlphaBetaPlayer()
    # white = player.IDDFSPlayer()

    board = play(white, black)
    print(board)

