from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

User = get_user_model()


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "user_id",
            type=int,
            help="User ID to import historical scrobbles for",
        )
        parser.add_argument(
            "--async",
            action="store_true",
            dest="async",
            help="Dispatch the task to Celery instead of running inline",
        )

    def handle(self, *args, **options):
        from scrobbles.importers.lastfm import dispatch_historical_imports

        user_id = options["user_id"]
        user = User.objects.filter(id=user_id).first()

        if not user:
            self.stderr.write(f"Error: User with ID {user_id} not found")
            return

        profile = user.profile
        if not profile.lastfm_username or not profile.lastfm_password:
            self.stderr.write(
                f"Error: User {user} does not have LastFM credentials configured"
            )
            return

        if options["async"]:
            dispatch_historical_imports.delay(user_id)
            self.stdout.write(
                self.style.SUCCESS(f"Dispatched historical import task for user {user}")
            )
        else:
            count = dispatch_historical_imports(user_id)
            self.stdout.write(
                self.style.SUCCESS(
                    f"Dispatched {count} monthly batch(es) for user {user}"
                )
            )
