from django.core.management.base import BaseCommand
from locations.models import GeoLocation
from scrobbles.tasks import reverse_geocode_geolocation


class Command(BaseCommand):
    help = "Enqueue reverse geocoding for GeoLocations missing a postal code"

    def add_arguments(self, parser):
        parser.add_argument(
            "--limit",
            type=int,
            default=0,
            help="Only enqueue the first N locations (default: all)",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Show what would be enqueued without enqueueing",
        )

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

        queryset = GeoLocation.objects.filter(postal_code__isnull=True).order_by(
            "-created"
        )
        if limit:
            queryset = queryset[:limit]

        total = queryset.count()
        self.stdout.write(f"Found {total} GeoLocations missing a postal code")

        enqueued = 0
        for location in queryset.iterator():
            if dry_run:
                self.stdout.write(
                    f"Would enqueue geo_location {location.id} "
                    f"({location.lat}, {location.lon})"
                )
            else:
                reverse_geocode_geolocation.delay(location.id)
            enqueued += 1

        if dry_run:
            self.stdout.write(self.style.WARNING("Dry run - no tasks enqueued"))
        else:
            self.stdout.write(
                self.style.SUCCESS(f"Enqueued {enqueued} reverse geocode tasks")
            )
