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

from matches.constants import MatchdayOperationStatus
from matches.matchday import MatchdayOperationsService
from matches.models import MatchdayOperation


class Command(BaseCommand):
    help = "Prepare, check in, or process FTG pre-match/matchday operations."

    def add_arguments(self, parser):
        parser.add_argument("--match-id")
        parser.add_argument("--prepare", action="store_true")
        parser.add_argument("--check-in-club-id")
        parser.add_argument("--due", action="store_true", help="Process all due open operations.")
        parser.add_argument("--no-auto-start", action="store_true")

    def handle(self, *args, **options):
        match_id = options.get("match_id")
        due = options.get("due")
        if not match_id and not due:
            raise CommandError("Provide --match-id or --due.")

        if match_id:
            if options.get("prepare"):
                MatchdayOperationsService.prepare_for_match(match_id=match_id)

            club_id = options.get("check_in_club_id")
            if club_id:
                state = MatchdayOperationsService.check_in(
                    match_id=match_id,
                    club_id=club_id,
                )
                self.stdout.write(
                    f"check-in {state.club_id}: {state.attendance_status}"
                )
            operation = MatchdayOperationsService.sync(
                match_id=match_id,
                auto_start=not options.get("no_auto_start"),
            )
            self.stdout.write(
                self.style.SUCCESS(f"{operation.match_id}: {operation.status}")
            )
            return

        now = timezone.now()
        terminal = [
            MatchdayOperationStatus.STARTED,
            MatchdayOperationStatus.CLOSED,
            MatchdayOperationStatus.CANCELLED,
            MatchdayOperationStatus.NO_SHOW_REVIEW,
        ]
        qs = (
            MatchdayOperation.objects
            .exclude(status__in=terminal)
            .filter(checkin_opens_at__lte=now)
            .order_by("kickoff_at", "match_id")
        )
        processed = 0
        for operation in qs.iterator():
            refreshed = MatchdayOperationsService.sync(
                match_id=operation.match_id,
                auto_start=not options.get("no_auto_start"),
            )
            processed += 1
            self.stdout.write(f"{refreshed.match_id}: {refreshed.status}")
        self.stdout.write(self.style.SUCCESS(f"processed={processed}"))
