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

from matches.constants import InteractiveMatchSessionStatus
from matches.interactive import InteractiveMatchRunnerService
from matches.models import InteractiveMatchSession


class Command(BaseCommand):
    help = "Advance interactive matches one deterministic checkpoint at a time."

    def add_arguments(self, parser):
        parser.add_argument("--match-id")
        parser.add_argument("--due", action="store_true")
        parser.add_argument("--force", action="store_true")

    def handle(self, *args, **options):
        match_id = options.get("match_id")
        due = options.get("due")
        if bool(match_id) == bool(due):
            raise CommandError("Provide exactly one of --match-id or --due.")
        if match_id:
            try:
                session, run = InteractiveMatchRunnerService.advance(
                    match_id=match_id, force=options.get("force", False)
                )
            except Exception as exc:
                raise CommandError(str(exc)) from exc
            suffix = f" completed run={run.pk}" if run else ""
            self.stdout.write(self.style.SUCCESS(
                f"{match_id}: segment={session.current_segment} minute={session.current_minute} "
                f"score={session.home_score}-{session.away_score}{suffix}"
            ))
            return

        now = timezone.now()
        qs = InteractiveMatchSession.objects.filter(
            status=InteractiveMatchSessionStatus.OPEN,
            next_advance_at__lte=now,
        ).order_by("next_advance_at", "match_id")
        advanced = completed = failed = 0
        for session in qs.iterator():
            try:
                updated, run = InteractiveMatchRunnerService.advance(
                    session_id=session.pk, now=now
                )
            except Exception as exc:
                failed += 1
                self.stderr.write(f"{session.match_id}: FAILED: {exc}")
                continue
            advanced += 1
            completed += int(run is not None)
            self.stdout.write(
                f"{session.match_id}: segment={updated.current_segment} "
                f"score={updated.home_score}-{updated.away_score}"
            )
        self.stdout.write(self.style.SUCCESS(
            f"advanced={advanced} completed={completed} failed={failed}"
        ))
