"""Adult first-team default XI and controlled matchday fallback.

The template is *not* a match lineup: it is a coach preference.  When a match
has no own lineup, a validated snapshot may be created at lineup deadline.
An explicit match draft (even incomplete) always wins over the template.
"""
from django.db import transaction
from django.utils import timezone

from clubs.models import Club, ClubDefaultLineup, ClubSquadMembership
from players.models import Player, Position
from leagues.constants import LeagueCompetitionType
from .constants import FORMATION_SLOTS, FormationCode, LineupStatus, LineupEntryRole, TacticalPlayerRole, MatchStatus
from .exceptions import InvalidLineupPlayerError, IncompleteLineupError


# Human-readable football role affinity; UI hints do not alter engine ratings.
_FITS = {
    'GK': ('GK',), 'LB': ('LB', 'CB', 'LM'), 'RB': ('RB', 'CB', 'RM'),
    'LCB': ('CB', 'LB', 'RB'), 'RCB': ('CB', 'RB', 'LB'), 'CB': ('CB', 'LB', 'RB'),
    'LWB': ('LB', 'LM', 'LW'), 'RWB': ('RB', 'RM', 'RW'),
    'LDM': ('CDM', 'CM', 'CB'), 'RDM': ('CDM', 'CM', 'CB'), 'DM': ('CDM', 'CM', 'CB'),
    'LCM': ('CM', 'CDM', 'CAM'), 'RCM': ('CM', 'CDM', 'CAM'), 'CM': ('CM', 'CDM', 'CAM'),
    'CAM': ('CAM', 'CM', 'CF'), 'LM': ('LM', 'LW', 'LB'), 'RM': ('RM', 'RW', 'RB'),
    'LW': ('LW', 'LM', 'ST'), 'RW': ('RW', 'RM', 'ST'),
    'ST': ('ST', 'CF', 'CAM'), 'LST': ('ST', 'CF', 'LW'), 'RST': ('ST', 'CF', 'RW'),
}


class DefaultLineupService:
    @staticmethod
    def _propose(club, *, match=None):
        players = list(Player.objects.filter(
            squad_membership__club_id=club.pk
        ).order_by('id'))
        if match is not None:
            from injuries.resolver import InjuryResolver
            players = [p for p in players if InjuryResolver.for_player(player=p).match_eligible]
        positions = FORMATION_SLOTS[FormationCode.FOUR_THREE_THREE]
        if len(players) < 21 or sum(p.position == Position.GK for p in players) < 2:
            raise IncompleteLineupError('At least 21 available squad players, including two goalkeepers, are needed.')
        remaining = {str(p.pk): p for p in players}
        # Start with the goalkeeper and specialist positions. Balanced, stable
        # role fit + overall; no pretend attribute or match-result projection.
        order = ['GK', 'LB', 'RB', 'LCB', 'RCB', 'LW', 'RW', 'ST', 'LCM', 'RCM', 'CM']
        chosen = {}
        for slot in order:
            pool = [p for p in remaining.values() if (p.position == Position.GK) == (slot == 'GK')]
            if not pool:
                raise IncompleteLineupError('Not enough eligible outfield players for an eleven.')
            allowed = _FITS[slot]
            def score(p):
                try:
                    priority = allowed.index(p.position)
                except ValueError:
                    priority = 5
                return (int(p.overall) + (35 if priority == 0 else 19 if priority == 1 else 7 if priority == 2 else -18), int(p.overall), str(p.pk))
            # Prefer role fit over raw overall; tie-breaker gives deterministic preview.
            player = max(pool, key=score)
            chosen[slot] = player
            remaining.pop(str(player.pk))
        starters = [{'slot': slot, 'player_id': str(chosen[slot].pk), 'tactical_role': 'AUTO'} for slot in positions]
        bench_pool = list(remaining.values())
        bench_pool.sort(key=lambda p: (p.position == Position.GK, int(p.overall), str(p.pk)), reverse=True)
        substitutes = [str(p.pk) for p in bench_pool[:10]]
        captain = max(chosen.values(), key=lambda p: (int(p.decision_making) + int(p.teamwork), int(p.overall), str(p.pk)))
        return {'formation': '4-3-3', 'starters': starters, 'substitutes': substitutes, 'captain_id': str(captain.pk)}

    @staticmethod
    def get_for_club(*, club, match=None):
        template = ClubDefaultLineup.objects.filter(club_id=club.pk).first()
        if template:
            ids = [str(row['player_id']) for row in template.starters] + [str(pk) for pk in template.substitutes]
            players = list(Player.objects.filter(pk__in=ids, squad_membership__club=club))
            valid = len(ids) == 21 and len(set(ids)) == 21 and len(players) == 21 and sum(p.position == Position.GK for p in players) >= 2
            return {
                'valid': valid, 'available': valid,
                'detail': '' if valid else 'Saved lineup is stale; select 21 current players including at least two goalkeepers.',
                'saved': True, 'source': 'SAVED', 'formation': template.formation,
                'starters': template.starters, 'substitutes': template.substitutes, 'tactical_plan': template.tactical_plan,
                'captain_id': str(template.captain_id), 'updated_at': template.updated_at,
            }
        try:
            suggested = DefaultLineupService._propose(club, match=match)
        except IncompleteLineupError as exc:
            return {'saved': False, 'source': 'AUTO', 'available': False,
                    'detail': str(exc), 'formation': '4-3-3',
                    'starters': [], 'substitutes': [], 'captain_id': None}
        return {'saved': False, 'source': 'AUTO', 'available': True, **suggested}

    @staticmethod
    @transaction.atomic
    def save(*, club, formation, starters, substitutes, captain_id, tactical_plan=None):
        from .lineups import (
            _validate_formation, _normalize_starters, _normalize_player_ids,
            _normalize_uuid, _ensure_unique_player_ids, _validate_slots_for_draft,
            _validate_required_position_compatibility,
        )
        formation = _validate_formation(formation)
        starters = _normalize_starters(starters)
        substitutes = _normalize_player_ids(substitutes, field_name='substitutes')
        captain_id = _normalize_uuid(captain_id, field_name='captain_id')
        allowed = set(FORMATION_SLOTS[formation])
        if len(starters) != 11 or (formation != FormationCode.CUSTOM and {row['slot'] for row in starters} != allowed) or (formation == FormationCode.CUSTOM and ('GK' not in {r['slot'] for r in starters} or not {r['slot'] for r in starters} <= allowed)):
            raise IncompleteLineupError('Default XI must contain all 11 formation positions.')
        if len(substitutes) != 10:
            raise InvalidLineupPlayerError('Default matchday squad requires exactly ten substitutes (21 players).')
        _validate_slots_for_draft(formation=formation, starter_rows=starters)
        ids = [row['player_id'] for row in starters] + substitutes
        _ensure_unique_player_ids(ids)
        if captain_id not in [row['player_id'] for row in starters]:
            raise InvalidLineupPlayerError('The captain must start the match.')
        Club.objects.select_for_update().get(pk=club.pk)
        members = set(str(pk) for pk in ClubSquadMembership.objects.filter(
            club_id=club.pk, player_id__in=ids
        ).values_list('player_id', flat=True))
        if len(members) != len(ids):
            raise InvalidLineupPlayerError('Every selected player must currently belong to the club.')
        players_by_id = {str(p.pk): p for p in Player.objects.filter(pk__in=ids)}
        if sum(p.position == Position.GK for p in players_by_id.values()) < 2:
            raise InvalidLineupPlayerError('Default squad requires at least two goalkeepers.')
        _validate_required_position_compatibility(starter_rows=starters, players_by_id=players_by_id)
        # Lock club before writing its one-to-one template, including first insert.
        Club.objects.select_for_update().get(pk=club.pk)
        from .tactical_catalog import validate_plan
        existing = ClubDefaultLineup.objects.filter(club=club).first()
        plan = validate_plan(tactical_plan if tactical_plan is not None else (existing.tactical_plan if existing else {}))
        ClubDefaultLineup.objects.update_or_create(
            club=club,
            defaults={'formation': formation, 'starters': starters, 'tactical_plan': plan,
                      'substitutes': substitutes, 'captain_id': captain_id},
        )
        return DefaultLineupService.get_for_club(club=club)

    @staticmethod
    def reset(*, club):
        ClubDefaultLineup.objects.filter(club=club).delete()

    @staticmethod
    def materialize_for_match(*, match, club_id, at=None):
        """Called only by trusted matchday orchestration while Match row is locked.

        Requires no existing match-specific lineup.  Missing/invalid adult XI
        fails closed; caller handles failure and records readiness evidence.
        """
        from .lineups import (MatchLineupService, _normalize_starters, _validate_slots_for_draft,
                              _validate_required_position_compatibility)
        from .models import MatchLineup, MatchLineupEntry
        if match.fixture.competition_type != LeagueCompetitionType.ADULT:
            return None  # Youth default requires separate academy participant.
        if match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            return None
        if MatchLineup.objects.filter(match_id=match.pk, club_id=club_id).exists():
            return None  # An explicit per-match draft always has priority.
        club = Club.objects.get(pk=club_id)
        data = DefaultLineupService.get_for_club(club=club, match=match)
        if not data.get('available', True) or len(data['starters']) != 11:
            raise IncompleteLineupError('No complete valid club default XI is available.')
        starter_rows = _normalize_starters(data['starters'])
        _validate_slots_for_draft(formation=data['formation'], starter_rows=starter_rows)
        ids = [s['player_id'] for s in starter_rows] + data['substitutes']
        from .lineups import _ensure_unique_player_ids
        _ensure_unique_player_ids(ids)
        players = MatchLineupService._validate_current_roster(
            match=match, club_id=str(club_id), participant_type=LeagueCompetitionType.ADULT,
            youth_team_id=None, player_ids=ids, lock_rows=False,
        )
        _validate_required_position_compatibility(starter_rows=starter_rows, players_by_id=players)
        lineup = MatchLineup.objects.create(
            match=match, club_id=club_id, participant_type=LeagueCompetitionType.ADULT,
            formation=data['formation'], status=LineupStatus.DRAFT,
        )
        MatchLineupEntry.objects.bulk_create([
            MatchLineupEntry(
                lineup=lineup, player_id=row['player_id'], role=LineupEntryRole.STARTER,
                tactical_role=row['tactical_role'], slot=row['slot'],
                is_captain=(row['player_id'] == data['captain_id']),
            ) for row in starter_rows
        ] + [
            MatchLineupEntry(
                lineup=lineup, player_id=pk, role=LineupEntryRole.SUBSTITUTE,
                tactical_role=TacticalPlayerRole.AUTO, slot='', is_captain=False,
            ) for pk in data['substitutes']
        ])
        from .tactical_catalog import apply_plan
        apply_plan(lineup, data.get("tactical_plan") or {})
        # Authoritative checks: injury, competition registration, lineups,
        # set pieces, captain and GK constraints. No auto-repair on failure.
        MatchLineupService._validate_complete_lineup(lineup, lock_roster=False)
        lineup.status = LineupStatus.SUBMITTED
        lineup.submitted_at = at or timezone.now()
        lineup.save(update_fields=['status', 'submitted_at', 'updated_at'])
        return lineup
