import logging
from otree.database import session_scope

from otree.bots.runner import run_all_bots_for_session_config
from otree.constants import AUTO_NAME_BOTS_EXPORT_FOLDER
from .base import BaseCommand

logger = logging.getLogger('otree')
MSG_BOTS_HELP = 'Run oTree bots'


class Command(BaseCommand):
    help = MSG_BOTS_HELP

    def add_arguments(self, parser):
        # Positional arguments
        parser.add_argument(
            'session_config_name',
            nargs='?',
            help='If omitted, all sessions in SESSION_CONFIGS are run',
        )

        parser.add_argument(
            'num_participants',
            type=int,
            nargs='?',
            help='Number of participants (if omitted, use num_demo_participants)',
        )

        # don't call it --data because then people might think that
        # that's the *input* data folder
        parser.add_argument(
            '--export',
            nargs='?',
            const=AUTO_NAME_BOTS_EXPORT_FOLDER,
            dest='export_path',
            help=(
                'Saves the data generated by the tests. '
                'Runs the "export data" command, '
                'outputting the CSV files to the specified directory, '
                'or an auto-generated one.'
            ),
        )
        parser.add_argument(
            '--save',
            nargs='?',
            const=AUTO_NAME_BOTS_EXPORT_FOLDER,
            dest='export_path',
            help=('Alias for --export.'),
        )

    def handle(self, *, session_config_name, num_participants, export_path, **options):

        run_all_bots_for_session_config(
            session_config_name=session_config_name,
            num_participants=num_participants,
            export_path=export_path,
        )
