from __future__ import annotations

from django.db import transaction

from .constants import CornerRoutine, FreeKickRoutine, LineupStatus
from .exceptions import InvalidLineupPlayerError, LineupNotEditableError
from .models import MatchLineup, MatchLineupEntry, MatchSetPiecePlan


class MatchSetPiecePlanService:
    """Authoritative editable pre-kickoff set-piece configuration."""

    @staticmethod
    @transaction.atomic
    def configure(
        *, lineup_id, penalty_taker_id=None, direct_free_kick_taker_id=None,
        left_corner_taker_id=None, right_corner_taker_id=None,
        aerial_target_player_id=None, penalty_order=(),
        corner_routine=CornerRoutine.MIXED, free_kick_routine=FreeKickRoutine.MIXED,
    ):
        lineup = (
            MatchLineup.objects.select_for_update()
            .select_related("match")
            .get(pk=lineup_id)
        )
        if lineup.status != LineupStatus.DRAFT:
            raise LineupNotEditableError("Set-piece plans can only be edited on a DRAFT lineup.")
        MatchSetPiecePlanService._validate_values(
            lineup=lineup,
            penalty_taker_id=penalty_taker_id,
            direct_free_kick_taker_id=direct_free_kick_taker_id,
            left_corner_taker_id=left_corner_taker_id,
            right_corner_taker_id=right_corner_taker_id,
            aerial_target_player_id=aerial_target_player_id,
            penalty_order=penalty_order,
            corner_routine=corner_routine,
            free_kick_routine=free_kick_routine,
        )
        plan, _ = MatchSetPiecePlan.objects.select_for_update().get_or_create(lineup=lineup)
        plan.penalty_taker_id = penalty_taker_id
        plan.direct_free_kick_taker_id = direct_free_kick_taker_id
        plan.left_corner_taker_id = left_corner_taker_id
        plan.right_corner_taker_id = right_corner_taker_id
        plan.aerial_target_player_id = aerial_target_player_id
        plan.penalty_order = [str(value) for value in penalty_order]
        plan.corner_routine = corner_routine
        plan.free_kick_routine = free_kick_routine
        plan.save()
        return plan

    @staticmethod
    def validate_for_lineup(lineup):
        try:
            plan = lineup.set_piece_plan
        except MatchSetPiecePlan.DoesNotExist:
            return None
        MatchSetPiecePlanService._validate_values(
            lineup=lineup,
            penalty_taker_id=plan.penalty_taker_id,
            direct_free_kick_taker_id=plan.direct_free_kick_taker_id,
            left_corner_taker_id=plan.left_corner_taker_id,
            right_corner_taker_id=plan.right_corner_taker_id,
            aerial_target_player_id=plan.aerial_target_player_id,
            penalty_order=plan.penalty_order,
            corner_routine=plan.corner_routine,
            free_kick_routine=plan.free_kick_routine,
        )
        return plan

    @staticmethod
    def _validate_values(*, lineup, penalty_taker_id, direct_free_kick_taker_id,
                         left_corner_taker_id, right_corner_taker_id,
                         aerial_target_player_id, penalty_order,
                         corner_routine, free_kick_routine):
        if corner_routine not in CornerRoutine.values:
            raise InvalidLineupPlayerError("Unsupported corner routine.")
        if free_kick_routine not in FreeKickRoutine.values:
            raise InvalidLineupPlayerError("Unsupported free-kick routine.")
        selected = {
            str(value)
            for value in MatchLineupEntry.objects.filter(lineup=lineup).values_list("player_id", flat=True)
        }
        named = {
            "penalty_taker_id": penalty_taker_id,
            "direct_free_kick_taker_id": direct_free_kick_taker_id,
            "left_corner_taker_id": left_corner_taker_id,
            "right_corner_taker_id": right_corner_taker_id,
            "aerial_target_player_id": aerial_target_player_id,
        }
        for field, value in named.items():
            if value is not None and str(value) not in selected:
                raise InvalidLineupPlayerError(f"{field} must reference a player selected in this lineup.")
        order = [str(value) for value in (penalty_order or [])]
        if len(order) > 11 or len(set(order)) != len(order):
            raise InvalidLineupPlayerError("Penalty order must contain at most 11 unique players.")
        if any(value not in selected for value in order):
            raise InvalidLineupPlayerError("Every penalty-order player must be selected in this lineup.")
