# -*- 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.saves.models import Association
from hotpocket_backend.apps.saves.services import AssociationsService
from hotpocket_soa.dto.associations import AssociationUpdateIn

LOGGER = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Data migration for BTHLABS-38'

    def add_arguments(self, parser: ArgumentParser):
        parser.add_argument(
            '-d', '--dry-run', action='store_true', default=False,
            help='Dry run',
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run', False)

        counters = {
            'migrated': 0,
            'errors': 0,
        }

        associations_service = AssociationsService()

        with django.db.transaction.atomic():
            for association in Association.objects.all():
                LOGGER.info('Migrating: `%s`', association)

                try:
                    update = AssociationUpdateIn.model_validate(dict(
                        target_title=(
                            association.target_title
                            if association.target_title is not None
                            else association.target_meta.get('title', None)
                        ),
                        target_description=(
                            association.target_description
                            if association.target_description is not None
                            else association.target_meta.get('description', None)
                        ),
                    ))

                    _ = associations_service.update(
                        pk=association.pk,
                        update=update,
                    )

                    counters['migrated'] = counters['migrated'] + 1
                except Exception as exception:
                    LOGGER.error(
                        'Unhandled exception: pk=`%s`: %s',
                        association.pk,
                        exception,
                        exc_info=exception,
                    )
                    counters['errors'] = counters['errors'] + 1

            LOGGER.info(
                'Done. Migrated: `%d`. Errors: `%d`',
                counters['migrated'],
                counters['errors'],
            )

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