from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.rides.services import RideRankingService


class Command(BaseCommand):
    help = "Calculates and updates ride rankings using the Internet Roller Coaster Poll algorithm"

    def add_arguments(self, parser):
        parser.add_argument(
            "--category",
            type=str,
            default=None,
            help="Optional ride category to filter (e.g., RC for roller coasters)",
        )

    def handle(self, *args, **options):
        category = options.get("category")

        service = RideRankingService()
        self.stdout.write(self.style.SUCCESS(f"Starting ride ranking calculation at {timezone.now().isoformat()}"))

        result = service.update_all_rankings(category=category)

        self.stdout.write(
            self.style.SUCCESS(
                f"Completed ranking calculation: {result.get('rides_ranked', 0)} rides ranked, "
                f"{result.get('comparisons_made', 0)} comparisons, "
                f"duration={result.get('duration', 0):.2f}s"
            )
        )
