from django.core.management.base import BaseCommand
from django.db import models
from scrobbles.models import Scrobble


class Command(BaseCommand):
    help = "Backfill tags on scrobbles from labels in their log data"

    def add_arguments(self, parser):
        parser.add_argument(
            "--commit",
            action="store_true",
            help="Actually update tags",
        )

    def handle(self, *args, **options):
        commit = options["commit"]

        scrobbles = Scrobble.objects.filter(
            models.Q(log__labels__isnull=False) & ~models.Q(log__labels=[])
        )

        updated_count = 0
        skipped_count = 0

        for scrobble in scrobbles:
            labels = scrobble.log.get("labels", [])
            if not labels:
                skipped_count += 1
                continue

            existing_tags = list(scrobble.tags.all().values_list("name", flat=True))
            new_labels = [label for label in labels if label not in existing_tags]

            if new_labels:
                updated_count += 1
                if commit:
                    for label in new_labels:
                        scrobble.tags.add(label)
                    self.stdout.write(
                        f"Updated scrobble {scrobble.id} with tags: {new_labels}"
                    )
                else:
                    self.stdout.write(
                        f"[DRY RUN] Would update scrobble {scrobble.id} with tags: {new_labels}"
                    )

        self.stdout.write(f"\nUpdated {updated_count} scrobbles")
        self.stdout.write(f"Skipped {skipped_count} scrobbles (no new labels)")
