#!/usr/bin/env python
import os
import sys, signal, argparse, logging

from pytictactoe.player.clever_player import CleverPlayer
from pytictactoe.player.cli_player import CliPlayer
from pytictactoe.player.defensive_player import DefensivePlayer
from pytictactoe.player.random_player import RandomPlayer
from pytictactoe.tournament import Tournament


def start_tournament(rounds, rl, model_path):
    tournament = Tournament(rounds=rounds)
    cli_player = RandomPlayer()
    if rl:
        from reinforcement_learning.rl_player import RlPlayer
        from reinforcement_learning.model import build_model
        model = build_model(model_path=model_path)
        opponent = RlPlayer(model=model)
    else:
        opponent = CleverPlayer()
    tournament.register_player(cli_player)
    tournament.register_player(opponent)
    tournament.play()


def set_logging():
    root = logging.getLogger()
    root.setLevel(logging.INFO)
    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(message)s')
    stream_handler.setFormatter(formatter)
    root.addHandler(stream_handler)


def handler(signum, frame):
    print('\n pytictactoe terminated!  Goodbye!')
    sys.exit(0)


if __name__ == "__main__":
    set_logging()
    dir_path = os.path.dirname(os.path.realpath(__file__))
    parent_dir = os.path.abspath(os.path.join(dir_path, os.pardir))
    signal.signal(signal.SIGINT, handler)
    parser = argparse.ArgumentParser(description='CLI pytictactoe', )
    parser.add_argument('-r', '--rounds', dest='rounds', type=int, help='Tournament rounds')
    parser.add_argument('-m', '--model_path', dest='model_path', help='Tournament rounds')
    parser.add_argument('--rl', dest='rl', action='store_true')
    parser.set_defaults(rounds=10000, rl=False,
                        model_path=parent_dir + '/reinforcement_learning/weights/rl_model_tictactoe.h5')
    args = parser.parse_args()
    start_tournament(args.rounds, args.rl, args.model_path)
