from django.core.management.base import BaseCommand

from people.models import PersonScrobble
from people.signals import get_person_ids_from_log
from scrobbles.models import Scrobble


class Command(BaseCommand):
    help = "Backfill PersonScrobble junction table from existing scrobbles"

    def handle(self, *args, **options):
        count = 0
        for scrobble in Scrobble.objects.all():
            person_ids = get_person_ids_from_log(scrobble.log)
            for person_id in person_ids:
                obj, created = PersonScrobble.objects.get_or_create(
                    person_id=person_id,
                    user=scrobble.user,
                    scrobble=scrobble,
                )
                if created:
                    count += 1
        self.stdout.write(f"Created {count} PersonScrobble records")
        self.stdout.write(self.style.SUCCESS("Done!"))
