from django.db.models import Q

from .exceptions import MatchNotFoundError
from .models import (
    Fixture,
    Match,
    MatchEvent,
    MatchLineup,
    MatchSimulationReport,
    MatchSimulationRun,
    MatchSimulationSnapshot,
)


def get_match(*, match_id):
    try:
        return (
            Match.objects.select_related(
                "fixture",
                "fixture__home_club",
                "fixture__away_club",
                "fixture__home_youth_team",
                "fixture__away_youth_team",
                "fixture__competition",
                "fixture__competition__league",
                "fixture__competition__season",
                "fixture__federation_competition",
                "fixture__federation_competition__federation",
                "fixture__federation_competition__season",
            )
            .get(pk=match_id)
        )
    except Match.DoesNotExist as exc:
        raise MatchNotFoundError("Match does not exist.") from exc


def get_competition_fixtures(*, competition):
    return (
        Fixture.objects.filter(competition=competition)
        .select_related(
            "home_club", "away_club", "home_youth_team", "away_youth_team", "competition"
        )
        .order_by("round_number", "home_club_id")
    )


def get_federation_competition_fixtures(*, competition):
    return (
        Fixture.objects.filter(federation_competition=competition)
        .select_related(
            "home_club", "away_club", "home_youth_team", "away_youth_team",
            "federation_competition",
        )
        .order_by("round_number", "id")
    )


def get_federation_competition_matches(*, competition, status=None):
    qs = (
        Match.objects.filter(fixture__federation_competition=competition)
        .select_related(
            "fixture", "fixture__home_club", "fixture__away_club",
            "fixture__home_youth_team", "fixture__away_youth_team",
        )
        .order_by("fixture__round_number", "fixture__id")
    )
    if status is not None:
        qs = qs.filter(status=status)
    return qs


def get_round_fixtures(*, competition, round_number):
    return get_competition_fixtures(competition=competition).filter(
        round_number=round_number
    )


def get_club_fixtures(*, competition, club):
    return get_competition_fixtures(competition=competition).filter(
        Q(home_club=club) | Q(away_club=club)
    )


def get_competition_matches(*, competition, status=None):
    qs = (
        Match.objects.filter(fixture__competition=competition)
        .select_related(
            "fixture",
            "fixture__home_club",
            "fixture__away_club",
            "fixture__home_youth_team",
            "fixture__away_youth_team",
        )
        .order_by("fixture__round_number", "fixture__home_club_id")
    )
    if status is not None:
        qs = qs.filter(status=status)
    return qs


def get_match_lineups(*, match):
    return (
        MatchLineup.objects.filter(match=match)
        .select_related("club", "youth_team", "match")
        .prefetch_related("entries__player")
        .order_by("club_id")
    )


def get_club_match_lineup(*, match, club):
    try:
        return (
            MatchLineup.objects.select_related("club", "youth_team", "match")
            .prefetch_related("entries__player")
            .get(match=match, club=club)
        )
    except MatchLineup.DoesNotExist as exc:
        from .exceptions import LineupNotFoundError

        raise LineupNotFoundError("Lineup does not exist.") from exc


def get_match_simulation_snapshot(*, match):
    try:
        return MatchSimulationSnapshot.objects.get(match=match)
    except MatchSimulationSnapshot.DoesNotExist as exc:
        from .exceptions import SimulationSnapshotNotFoundError

        raise SimulationSnapshotNotFoundError(
            "Match has no kickoff simulation snapshot."
        ) from exc


def get_match_simulation_run(*, match):
    try:
        return MatchSimulationRun.objects.select_related("snapshot").get(
            snapshot__match=match
        )
    except MatchSimulationRun.DoesNotExist as exc:
        from .exceptions import SimulationSnapshotNotFoundError

        raise SimulationSnapshotNotFoundError(
            "Match has no persisted simulation result."
        ) from exc


def get_match_simulation_report(*, match):
    try:
        return (
            MatchSimulationReport.objects
            .select_related("run", "run__snapshot")
            .get(run__snapshot__match=match)
        )
    except MatchSimulationReport.DoesNotExist as exc:
        from .exceptions import SimulationReportError

        raise SimulationReportError("Match has no persisted simulation report.") from exc


def get_match_events(*, match):
    return (
        MatchEvent.objects.filter(match=match)
        .select_related("club", "player", "secondary_player", "report")
        .order_by("sequence")
    )


def match_schedule_history(*, match_id):
    from .models import MatchScheduleRevision
    return (
        MatchScheduleRevision.objects.filter(match_id=match_id)
        .select_related("calendar_slot", "performed_by")
        .order_by("revision_number")
    )


def get_matchday_operation(*, match_id):
    from .models import MatchdayOperation
    try:
        return (
            MatchdayOperation.objects
            .select_related("match", "profile", "match__fixture__home_club", "match__fixture__away_club")
            .prefetch_related("team_states", "eligibility_checks", "audit_events")
            .get(match_id=match_id)
        )
    except MatchdayOperation.DoesNotExist as exc:
        from .exceptions import MatchdayNotPreparedError
        raise MatchdayNotPreparedError("Matchday operation has not been prepared.") from exc


def get_matchday_team_states(*, match_id):
    from .models import MatchdayTeamState
    return (
        MatchdayTeamState.objects
        .filter(operation__match_id=match_id)
        .select_related("club", "operation")
        .order_by("club_id")
    )


def get_matchday_audit_history(*, match_id):
    from .models import MatchdayAuditEvent
    return (
        MatchdayAuditEvent.objects
        .filter(operation__match_id=match_id)
        .select_related("club", "performed_by", "operation")
        .order_by("sequence")
    )


def get_matchday_eligibility_history(*, match_id, club_id=None):
    from .models import MatchdayEligibilityCheck
    qs = (
        MatchdayEligibilityCheck.objects
        .filter(operation__match_id=match_id)
        .select_related("club", "operation")
        .order_by("club_id", "revision_number")
    )
    if club_id is not None:
        qs = qs.filter(club_id=club_id)
    return qs


def get_active_match_suspensions(*, match_id, player_id=None):
    from .models import PlayerMatchSuspension
    qs = (
        PlayerMatchSuspension.objects
        .filter(match_id=match_id, revocation__isnull=True)
        .select_related("player", "issued_by")
        .order_by("player_id")
    )
    if player_id is not None:
        qs = qs.filter(player_id=player_id)
    return qs


def get_match_discipline(*, match_id):
    from .models import DisciplineProcessingRun, DisciplinaryCardEvent
    cards = (
        DisciplinaryCardEvent.objects.filter(match_id=match_id)
        .select_related("player", "club", "revocation")
        .order_by("sequence")
    )
    run = DisciplineProcessingRun.objects.filter(match_id=match_id).first()
    return {"cards": cards, "processing_run": run}


def get_player_disciplinary_sanctions(*, player_id, active_only=False):
    from .models import PlayerDisciplinarySanction
    qs = (
        PlayerDisciplinarySanction.objects.filter(player_id=player_id)
        .select_related(
            "source_match", "source_card", "club_at_issue",
            "league_competition", "federation_competition",
        )
        .prefetch_related("assignments__suspension")
        .order_by("created_at", "id")
    )
    if active_only:
        qs = qs.filter(revocation__isnull=True)
    return qs


def get_match_administrative_decision(*, match_id):
    from .models import MatchAdministrativeDecision
    return MatchAdministrativeDecision.objects.filter(match_id=match_id).first()


def get_match_sporting_resolution(*, match_id):
    from .models import MatchSportingResolution
    return MatchSportingResolution.objects.filter(match_id=match_id).first()



def get_match_tactical_plans(*, match_id):
    from .models import MatchTacticalPlan
    return (
        MatchTacticalPlan.objects.filter(lineup__match_id=match_id)
        .select_related("lineup", "lineup__club")
        .prefetch_related("instructions")
        .order_by("lineup__club_id")
    )


def get_match_tactical_contexts(*, match_id):
    from .models import MatchTacticalContextSnapshot
    return (
        MatchTacticalContextSnapshot.objects.filter(match_id=match_id)
        .select_related("club", "lineup", "plan", "head_coach_assignment", "assistant_coach_assignment", "analyst_assignment")
        .order_by("club_id")
    )


def get_match_tactical_decisions(*, match_id):
    from .models import MatchTacticalDecision
    return (
        MatchTacticalDecision.objects.filter(match_id=match_id)
        .select_related("club", "run")
        .order_by("sequence")
    )


def get_interactive_match_session(*, match_id):
    from .models import InteractiveMatchSession
    try:
        return (
            InteractiveMatchSession.objects
            .select_related(
                "match__fixture__home_club",
                "match__fixture__away_club",
                "snapshot",
            )
            .prefetch_related("commands", "checkpoints")
            .get(match_id=match_id)
        )
    except InteractiveMatchSession.DoesNotExist as exc:
        from .exceptions import InteractiveMatchSessionNotFoundError
        raise InteractiveMatchSessionNotFoundError("Interactive session does not exist.") from exc


def get_live_match_commands(*, match_id, club_id=None):
    from .models import LiveMatchCommand
    qs = (
        LiveMatchCommand.objects.filter(session__match_id=match_id)
        .select_related("club", "actor", "session")
        .order_by("sequence")
    )
    if club_id is not None:
        qs = qs.filter(club_id=club_id)
    return qs


def get_interactive_match_checkpoints(*, match_id):
    from .models import InteractiveMatchCheckpoint
    return (
        InteractiveMatchCheckpoint.objects.filter(session__match_id=match_id)
        .select_related("session")
        .order_by("segment")
    )


def get_live_match_stream_events(*, match_id, after_sequence=0):
    from .models import LiveMatchStreamEvent
    return (
        LiveMatchStreamEvent.objects.filter(
            session__match_id=match_id,
            sequence__gt=after_sequence,
        )
        .select_related("session", "club")
        .order_by("sequence")
    )
