import logging
import time

from django.core.management.base import BaseCommand

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Refresh board game metadata from BGG (categories→genres, families→tags)"

    def add_arguments(self, parser):
        parser.add_argument(
            "--commit",
            action="store_true",
            help="Persist changes to the database",
        )
        parser.add_argument(
            "--force",
            action="store_true",
            help="Update all games even if they already have a published_date",
        )
        parser.add_argument(
            "--batch-size",
            type=int,
            default=50,
            help="Number of games to process per batch (default: 50)",
        )
        parser.add_argument(
            "--sleep",
            type=float,
            default=1.0,
            help="Seconds to sleep between API calls (default: 1.0)",
        )

    def handle(self, *args, **options):
        from boardgames.models import BoardGame

        commit = options["commit"]
        force = options["force"]
        batch_size = options["batch_size"]
        sleep_secs = options["sleep"]

        qs = BoardGame.objects.exclude(bggeek_id__isnull=True).exclude(bggeek_id="")
        total = qs.count()
        self.stdout.write(f"Found {total} board games with BGG IDs")

        if not commit:
            self.stdout.write(
                "Dry run — no API calls will be made. Use --commit to run lookups."
            )
            return

        enriched = 0
        skipped = 0

        for batch_num, offset in enumerate(range(0, total, batch_size)):
            batch = qs[offset : offset + batch_size]
            for game in batch:
                try:
                    game.fix_metadata(force_update=force)
                    enriched += 1
                except Exception as e:
                    self.stdout.write(
                        self.style.WARNING(
                            f"  [SKIPPED] {game.title} (BGG {game.bggeek_id}): {e}"
                        )
                    )
                    skipped += 1
                time.sleep(sleep_secs)

            self.stdout.write(
                f"  Batch {batch_num + 1}: {offset + len(batch)}/{total} — "
                f"enriched: {enriched}, skipped: {skipped}"
            )

        self.stdout.write(
            f"\nResults:\n"
            f"  Games enriched: {enriched}\n"
            f"  Games skipped:  {skipped}"
        )
