import logging

from django.core.management.base import BaseCommand

from boardgames.models import BoardGame
from boardgames.sources.bgg import lookup_boardgame_from_bgg
from boardgames.utils import fetch_and_link_expansions

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Fetch and link expansions for existing board games from BGG"

    def add_arguments(self, parser):
        parser.add_argument(
            "--commit",
            action="store_true",
            help="Persist changes to the database",
        )
        parser.add_argument(
            "--bggeek-id",
            type=str,
            help="Only process a single game by BGG ID",
        )

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

        games = (
            BoardGame.objects.exclude(bggeek_id__isnull=True)
            .exclude(bggeek_id="")
            .exclude(skip_expansions=True)
        )
        if bggeek_id:
            games = games.filter(bggeek_id=bggeek_id)

        total = games.count()
        self.stdout.write(f"Found {total} board games with BGG IDs")

        if total == 0:
            return

        updated = 0
        for game in games.iterator(chunk_size=100):
            try:
                data = lookup_boardgame_from_bgg(lookup_id=str(game.bggeek_id))
            except Exception as e:
                self.stdout.write(
                    self.style.WARNING(
                        f"Failed to fetch BGG data for {game.title} ({game.bggeek_id}): {e}"
                    )
                )
                continue

            expansions = data.get("expansions", [])
            if not expansions:
                continue

            if commit:
                fetch_and_link_expansions(game, expansions)
                updated += 1
                self.stdout.write(
                    f"  Linked {len(expansions)} expansions to {game.title}"
                )
            else:
                self.stdout.write(
                    f"  Would link {len(expansions)} expansions to {game.title}"
                )
                updated += 1

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