#! /usr/bin/env python3

# This file is part of pybayesbandit.

# pybayesbandit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# pybayesbandit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with pybayesbandit. If not, see <http://www.gnu.org/licenses/>.


from pybayesbandit.bandits.bernoulli import BernoulliBandit
from pybayesbandit.learners.random import RandomPolicy
from pybayesbandit.learners.ucb import UCBPolicy
from pybayesbandit.learners.thompson import ThompsonSamplingPolicy
from pybayesbandit.learners.vi import BetaBernoulliVIPolicy
from pybayesbandit.learners.uct import BetaBernoulliUCTPolicy
from pybayesbandit.learners.rollout import RolloutPolicy
from pybayesbandit.learners.lookahead import LookaheadTreeSearchPolicy
from pybayesbandit.games.totalregret import TotalRegretGame
from pybayesbandit.games.simpleregret import SimpleRegretGame

import argparse
import matplotlib.pyplot as plt
import time


def parse_args():
    description = 'Bayesian bandits in Python3.'
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument(
        'learner',
        type=str, choices=['random', 'ucb', 'thompson', 'vi', 'uct', 'rollout', 'aotree'],
        help='learner type'
    )
    parser.add_argument(
        'bandit',
        type=str, choices=['bernoulli'],
        help='bandit type'
    )
    parser.add_argument(
        'game',
        type=str, choices=['total', 'simple'],
        help='game setting'
    )
    parser.add_argument(
        '-p', '--params',
        nargs='+', type=float, default=[],
        help='bandit parameters'
    )
    parser.add_argument(
        '-d', '--maxdepth',
        type=int, default=10,
        help='maximum number of timesteps in the tree lookahead (default=10)'
    )
    parser.add_argument(
        '-t', '--trials',
        type=int, default=30,
        help='number of trials in Monte-Carlo sampling (default=30)'
    )
    parser.add_argument(
        '-C',
        type=float, default=2.0,
        help='UCT exploration constant (default=2.0)'
    )
    parser.add_argument(
        '-e', '--episodes',
        type=int, default=200,
        help='number of simulation episodes (default=200)'
    )
    parser.add_argument(
        '-hr', '--horizon',
        type=int, default=100,
        help='number of timesteps in each episode (default=100)'
    )
    parser.add_argument(
        '--plot',
        action='store_true',
        help='plot cumulative regret'
    )
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='verbose mode'
    )
    return parser.parse_args()


def show_args(args):
    if args.verbose:
        if args.learner == 'uct':
            print('>> learner  = {}(trials={}, maxdepth={}, C={})'.format(args.learner, args.trials, args.maxdepth, args.C))
        else:
            print('>> learner  = {}'.format(args.learner))
        print('>> bandit   = {}({})'.format(args.bandit, args.params))
        print('>> episodes = {}'.format(args.episodes))
        print('>> horizon  = {}'.format(args.horizon))


def make_bandit(args):
    bandits = {
        'bernoulli': BernoulliBandit
    }
    model = bandits[args.bandit]
    probs = args.params
    return model(probs)


def make_learner(args):
    learners = {
        'random': RandomPolicy,
        'ucb': UCBPolicy,
        'thompson': ThompsonSamplingPolicy,
        'vi': BetaBernoulliVIPolicy,
        'uct': BetaBernoulliUCTPolicy,
        'rollout': RolloutPolicy,
        'aotree': LookaheadTreeSearchPolicy
    }
    policy = learners[args.learner]
    actions = len(args.params)
    return policy(actions, args.horizon, args)


def make_game(args, bandit, learner):
    games = {
        'total': TotalRegretGame,
        'simple': SimpleRegretGame
    }
    return games[args.game](bandit, learner)


def report(args, results):
    print('Results:')
    if args.game == 'total':
        rewards, regrets = results
        print('>> Reward = {:8.4f} ± {:3.4f}'.format(rewards[0][-1], rewards[1][-1]))
        print('>> Regret = {:8.4f} ± {:3.4f}'.format(regrets[0][-1], regrets[1][-1]))
        print()
    elif args.game == 'simple':
        avg_simple_regret, std_simple_regret = results
        print('>> Simple regret = {:8.4f} ± {:3.4f}'.format(avg_simple_regret, std_simple_regret))


def plot(args, results):
    if args.game == 'total':
        plt.plot(results[1][0])
        plt.title('Regret', fontweight='bold')
        plt.ylabel('cumulative regret')
        plt.xlabel('rounds (t)')
        plt.grid()
        plt.tight_layout()
        plt.show()


if __name__ == '__main__':
    args = parse_args()

    print('\nRunning pybayesbandit ...')
    show_args(args)

    start = time.time()

    bandit = make_bandit(args)
    learner = make_learner(args)
    game = make_game(args, bandit, learner)

    results = game.run(args.episodes, args.horizon)

    end = time.time()
    print('Done in {:.3f} sec.\n'.format(end - start))

    report(args, results)
    if args.plot:
        plot(args, results)
