from datetime import date, time

from django.core.management.base import BaseCommand, CommandError

from matches.kickoff_scheduling import CompetitionKickoffSchedulingService


class Command(BaseCommand):
    help = "Assign exact kickoff timestamps from Season calendar windows."

    def add_arguments(self, parser):
        parser.add_argument("--season-id")
        parser.add_argument("--match-id")
        parser.add_argument("--date")
        parser.add_argument("--time")
        parser.add_argument("--timezone")
        parser.add_argument("--reason")

    def handle(self, *args, **options):
        season_id = options.get("season_id")
        match_id = options.get("match_id")
        if bool(season_id) == bool(match_id):
            raise CommandError("Provide exactly one of --season-id or --match-id.")

        if season_id:
            result = CompetitionKickoffSchedulingService.schedule_season(season_id=season_id)
            self.stdout.write(self.style.SUCCESS(str(result)))
            return

        if options.get("date") or options.get("time") or options.get("reason"):
            if not all([options.get("date"), options.get("time"), options.get("reason")]):
                raise CommandError("Manual reschedule requires --date, --time and --reason.")
            match = CompetitionKickoffSchedulingService.reschedule(
                match_id=match_id,
                local_date=date.fromisoformat(options["date"]),
                local_time=time.fromisoformat(options["time"]),
                timezone_name=options.get("timezone"),
                reason_text=options["reason"],
            )
        else:
            match = CompetitionKickoffSchedulingService.schedule_match_from_calendar(match_id=match_id)
        self.stdout.write(self.style.SUCCESS(f"{match.pk}: {match.scheduled_at.isoformat()}"))
