import logging

from django.core.management.base import BaseCommand

from boardgames.utils import board_names_to_variants
from scrobbles.models import Scrobble

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Convert existing board scrobble log 'board' keys to 'variant_ids'"

    def add_arguments(self, parser):
        parser.add_argument(
            "--commit",
            action="store_true",
            help="Persist changes to the database",
        )

    def handle(self, *args, **options):
        commit = options.get("commit", False)

        board_scrobbles = Scrobble.objects.filter(
            board_game__isnull=False,
            log__board__isnull=False,
        ).exclude(log__board="")

        total = board_scrobbles.count()
        self.stdout.write(f"Found {total} scrobbles with a 'board' key in log data")

        if total == 0:
            return

        updated = 0
        for scrobble in board_scrobbles.iterator(chunk_size=100):
            log = scrobble.log
            board_value = log.pop("board", None)
            if not board_value:
                continue

            variant_ids = board_names_to_variants(
                scrobble.board_game, [board_value]
            )
            if variant_ids:
                log["variant_ids"] = variant_ids

            if commit:
                Scrobble.objects.filter(pk=scrobble.pk).update(log=log)
                updated += 1
            else:
                updated += 1

        if commit:
            self.stdout.write(
                self.style.SUCCESS(
                    f"Updated {updated} scrobbles (changes committed)"
                )
            )
        else:
            self.stdout.write(
                f"Would update {updated} scrobbles (pass --commit to persist)"
            )
