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


class Command(BaseCommand):
    help = "Find videos with duplicate imdb_id values and merge scrobbles to the newest video"

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Show what would be done without making changes",
        )
        parser.add_argument(
            "--auto",
            action="store_true",
            help="Automatically fix duplicates without prompting",
        )

    def handle(self, *args, **options):
        from collections import defaultdict

        from videos.models import Video

        dry_run = options["dry_run"]
        auto = options["auto"]

        duplicate_imdb_ids = (
            Video.objects.filter(imdb_id__isnull=False)
            .exclude(imdb_id="")
            .values("imdb_id")
            .annotate(count=models.Count("id"))
            .filter(count__gt=1)
        )

        if not duplicate_imdb_ids.exists():
            self.stdout.write("No duplicate imdb_id values found")
            return

        self.stdout.write(
            f"Found {duplicate_imdb_ids.count()} imdb_ids with duplicates"
        )

        for dup in duplicate_imdb_ids:
            imdb_id = dup["imdb_id"]
            videos = list(Video.objects.filter(imdb_id=imdb_id).order_by("created"))

            self.stdout.write(f"\nimdb_id: {imdb_id}")
            self.stdout.write(f"  Found {len(videos)} videos:")

            for v in videos:
                scrobble_count = v.scrobble_set.count()
                self.stdout.write(
                    f"    id={v.id}, title='{v.title}', created={v.created}, scrobbles={scrobble_count}"
                )

            keeper = videos[-1]
            duplicates = videos[:-1]

            self.stdout.write(f"  Keeping: id={keeper.id} ('{keeper.title}')")
            self.stdout.write(f"  Merging from: {[d.id for d in duplicates]}")

            if dry_run:
                self.stdout.write(
                    self.style.WARNING("  [DRY RUN] Would move scrobbles")
                )
                continue

            if not auto:
                confirm = input("  Move scrobbles from duplicates to keeper? [y/N] ")
                if confirm.lower() != "y":
                    self.stdout.write("  Skipped")
                    continue

            for dup_video in duplicates:
                scrobble_count = dup_video.scrobble_set.count()
                if scrobble_count > 0:
                    dup_video.scrobble_set.update(video=keeper)
                    self.stdout.write(
                        f"    Moved {scrobble_count} scrobbles from id={dup_video.id} to id={keeper.id}"
                    )

                with connection.cursor() as cursor:
                    cursor.execute(
                        "DELETE FROM videos_video WHERE id = %s", [dup_video.id]
                    )
                self.stdout.write(f"    Deleted video id={dup_video.id}")

        self.stdout.write(self.style.SUCCESS("\nDone!"))
