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

from matches.constants import MatchExecutionMode, MatchStatus
from matches.models import Match, MatchSimulationSnapshot
from matches.simulation import MatchSimulationService


class Command(BaseCommand):
    help = "Run authoritative FTG match simulation; auto selects the newest engine compatible with each kickoff snapshot."

    def add_arguments(self, parser):
        parser.add_argument("--match-id")
        parser.add_argument("--due", action="store_true")
        parser.add_argument("--engine", choices=["auto", "v1", "v2", "v21", "v3"], default="auto")
        parser.add_argument("--skip-discipline", action="store_true")
        parser.add_argument("--skip-injuries", action="store_true")

    def _resolved_engine(self, match_id, requested):
        if requested != "auto":
            return requested
        try:
            schema = MatchSimulationSnapshot.objects.only("schema_version").get(match_id=match_id).schema_version
        except MatchSimulationSnapshot.DoesNotExist as exc:
            raise CommandError("Match has no kickoff simulation snapshot.") from exc
        if schema >= 3:
            return "v3"
        if schema >= 2:
            return "v2"
        return "v1"

    def _simulate(self, match_id, options):
        engine = self._resolved_engine(match_id, options["engine"])
        if engine == "v1":
            return MatchSimulationService.simulate_v1(match_id=match_id)
        if engine == "v2":
            return MatchSimulationService.simulate_v2(
                match_id=match_id,
                finalize_discipline=not options["skip_discipline"],
                project_injuries=not options["skip_injuries"],
            )
        if engine == "v21":
            return MatchSimulationService.simulate_v21(
                match_id=match_id,
                finalize_discipline=not options["skip_discipline"],
                project_injuries=not options["skip_injuries"],
            )
        return MatchSimulationService.simulate_v3(
            match_id=match_id,
            finalize_discipline=not options["skip_discipline"],
            project_injuries=not options["skip_injuries"],
        )

    def handle(self, *args, **options):
        match_id = options.get("match_id")
        if bool(match_id) == bool(options.get("due")):
            raise CommandError("Provide exactly one of --match-id or --due.")
        if match_id:
            try:
                run = self._simulate(match_id, options)
            except Exception as exc:
                raise CommandError(str(exc)) from exc
            self.stdout.write(self.style.SUCCESS(
                f"Simulation {run.pk} persisted with {run.engine_key}@{run.engine_version}."
            ))
            return

        qs = (
            Match.objects.filter(
                status=MatchStatus.IN_PROGRESS,
                execution_mode=MatchExecutionMode.AUTO,
                simulation_snapshot__isnull=False,
                simulation_snapshot__simulation_run__isnull=True,
            )
            .order_by("started_at", "id")
        )
        resolved = 0
        for match in qs.iterator():
            try:
                run = self._simulate(match.pk, options)
            except Exception as exc:
                self.stderr.write(f"{match.pk}: FAILED: {exc}")
                continue
            resolved += 1
            self.stdout.write(f"{match.pk}: {run.engine_key}@{run.engine_version}")
        self.stdout.write(self.style.SUCCESS(f"resolved={resolved}"))
