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

from game_statistics.models import MatchAnalyticsRun
from players.dynamics_services import PlayerDynamicsService
from players.models import PlayerMatchDynamicEffect


class Command(BaseCommand):
    help = "Project or backfill player form, morale and match experience."

    def add_arguments(self, parser):
        parser.add_argument("--match-id")
        parser.add_argument("--due", action="store_true")
        parser.add_argument("--limit", type=int, default=200)
        parser.add_argument("--verify", action="store_true")

    def handle(self, *args, **options):
        match_id = options.get("match_id")
        if match_id:
            effects = PlayerDynamicsService.project_match(match_id=match_id)
            if options["verify"]:
                PlayerDynamicsService._verify_effects(effects)
            self.stdout.write(self.style.SUCCESS(f"Projected {len(effects)} player effects for {match_id}."))
            return
        if not options["due"]:
            raise CommandError("Use --match-id or --due.")
        limit = max(1, min(int(options["limit"]), 5000))
        projected_match_ids = PlayerMatchDynamicEffect.objects.values_list("match_id", flat=True).distinct()
        runs = (
            MatchAnalyticsRun.objects.exclude(match_id__in=projected_match_ids)
            .select_related("match")
            .order_by("match__completed_at", "created_at")[:limit]
        )
        count = 0
        for run in runs:
            effects = PlayerDynamicsService.project_match(match_id=run.match_id)
            if options["verify"]:
                PlayerDynamicsService._verify_effects(effects)
            count += 1
        self.stdout.write(self.style.SUCCESS(f"Projected player dynamics for {count} matches."))
