# -*- coding: utf-8 -*-
from __future__ import annotations

from argparse import ArgumentParser
import logging

from django.core.management import BaseCommand
import django.db

from hotpocket_backend.apps.accounts.models import Account
from hotpocket_backend.apps.core.conf import settings

LOGGER = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Create initial Account'

    def add_arguments(self, parser: ArgumentParser):
        parser.add_argument(
            '-u', '--username', default=None,
            help='Override username for the Account',
        )
        parser.add_argument(
            '-p', '--password', default=None,
            help='Override Password for the Account',
        )
        parser.add_argument(
            '-d', '--dry-run', action='store_true', default=False,
            help='Dry run',
        )

    def handle(self, *args, **options):
        LOGGER.debug('args=`%s` options=`%s`', args, options)
        dry_run = options.get('dry_run', False)

        username = options.get('username') or settings.SECRETS.INITIAL_ACCOUNT.username
        if not username:
            LOGGER.info('Not creating initial Account: empty `username`')
            return

        password = options.get('password') or settings.SECRETS.INITIAL_ACCOUNT.password
        assert password, 'Unable to proceed: empty `password`'

        LOGGER.debug(
            'Creating initial Account: username=`%s` password=`%s`',
            username,
            password,
        )

        with django.db.transaction.atomic():
            current_account = Account.objects.filter(username=username).first()
            if current_account is not None:
                LOGGER.info(
                    'Account already exists: account=`%s`', current_account,
                )
                return

            account = Account.objects.create(
                username=username,
                first_name=username,
                is_superuser=True,
                is_staff=True,
            )
            account.set_password(password)
            account.save()

            LOGGER.info(
                'Account created: account=`%s`', account,
            )

            if dry_run is True:
                raise RuntimeError('DRY RUN')
