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

from scrobbles.models import Scrobble
from scrobbles.utils import analyze_scrobble_sentiment


class Command(BaseCommand):
    help = "Backfill VADER sentiment analysis for scrobbles with notes"

    def add_arguments(self, parser):
        parser.add_argument(
            "--commit",
            action="store_true",
            help="Actually update scrobble logs with sentiment data",
        )
        parser.add_argument(
            "--overwrite",
            action="store_true",
            help="Re-analyze scrobbles that already have sentiment data",
        )

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

        qs = Scrobble.objects.filter(
            ~models.Q(log__notes__isnull=True)
            & ~models.Q(log__notes=[])
            & ~models.Q(log__notes={})
        )
        if not overwrite:
            qs = qs.filter(log__sentiment__isnull=True)

        total = qs.count()
        analyzed_count = 0
        skipped_count = 0

        self.stdout.write(f"Found {total} scrobbles to process")

        for scrobble in qs.iterator():
            if commit:
                analyzed = analyze_scrobble_sentiment(scrobble, overwrite=overwrite)
            else:
                notes_str = ""
                if scrobble.logdata:
                    notes_str = scrobble.logdata.notes_as_str()
                analyzed = bool(notes_str)

            if analyzed:
                analyzed_count += 1
                if commit:
                    scores = (scrobble.log or {}).get("sentiment", {})
                    self.stdout.write(
                        f"  Updated scrobble {scrobble.id}: compound={scores.get('compound', 'N/A')}"
                    )
                else:
                    self.stdout.write(
                        f"  [DRY RUN] Would analyze scrobble {scrobble.id}"
                    )
            else:
                skipped_count += 1

        self.stdout.write(
            f"\nAnalyzed {analyzed_count} scrobbles, skipped {skipped_count}"
        )
        if not commit:
            self.stdout.write("Run with --commit to persist changes")
