from django.db import IntegrityError, transaction
from django.utils import timezone

from leagues.constants import (
    LeagueCompetitionStatus,
    LeagueStatus,
)
from leagues.models import League, LeagueCompetition
from leagues.scheduling import HomeAwayRoundRobinScheduler
from leagues.services import LeagueRegistrationService
from seasons.constants import SeasonStatus
from seasons.models import Season

from .constants import LEAGUE_FIXTURE_COUNT, MatchResultType, MatchStatus
from .exceptions import (
    CompetitionNotCompletableError,
    FixtureGenerationNotAllowedError,
    FixtureIntegrityError,
    MatchNotCancellableError,
    MatchNotCompletableError,
    MatchNotFoundError,
    MatchNotSchedulableError,
    MatchNotStartableError,
)
from .models import Fixture, Match
from .competition_support import (
    competition_is_schedulable, competition_is_startable,
    lock_competition_source_and_match, mark_started_if_needed,
)
from .validators import validate_kickoff, validate_score


class LeagueFixtureGenerationService:
    """Persist the deterministic League scheduler as Fixtures + Match stubs."""

    ALLOWED_SEASON_STATUSES = {SeasonStatus.DRAFT, SeasonStatus.UPCOMING}

    @staticmethod
    @transaction.atomic
    def generate(*, league_id, season_id):
        try:
            league = League.objects.select_for_update().get(pk=league_id)
        except League.DoesNotExist as exc:
            raise FixtureGenerationNotAllowedError("League does not exist.") from exc

        try:
            season = Season.objects.select_for_update().get(pk=season_id)
        except Season.DoesNotExist as exc:
            raise FixtureGenerationNotAllowedError("Season does not exist.") from exc

        if league.status != LeagueStatus.ACTIVE:
            raise FixtureGenerationNotAllowedError(
                "Fixtures can only be generated for an ACTIVE league."
            )
        if season.status not in LeagueFixtureGenerationService.ALLOWED_SEASON_STATUSES:
            raise FixtureGenerationNotAllowedError(
                "League fixtures must be generated before the Season becomes ACTIVE."
            )

        LeagueRegistrationService.validate_ready(league=league, season=season)

        competition = (
            LeagueCompetition.objects.select_for_update()
            .filter(league=league, season=season)
            .first()
        )
        if competition is None:
            competition = LeagueCompetition.objects.create(
                league=league,
                season=season,
                status=LeagueCompetitionStatus.DRAFT,
            )

        if competition.fixtures_generated_at is not None:
            LeagueFixtureGenerationService._verify_existing_schedule(competition)
            return competition

        if competition.status != LeagueCompetitionStatus.DRAFT:
            raise FixtureIntegrityError(
                "Competition is not in DRAFT state before fixture generation."
            )

        if Fixture.objects.filter(competition=competition).exists():
            raise FixtureIntegrityError(
                "Competition contains fixtures without a completed generation marker."
            )

        slots = HomeAwayRoundRobinScheduler.build(league=league, season=season)
        if len(slots) != LEAGUE_FIXTURE_COUNT:
            raise FixtureIntegrityError(
                f"Expected {LEAGUE_FIXTURE_COUNT} league fixture slots."
            )

        fixtures = [
            Fixture(
                competition=competition,
                round_number=slot.round_number,
                leg=slot.leg,
                home_club_id=slot.home_club_id,
                away_club_id=slot.away_club_id,
                competition_type=league.competition_type,
                home_youth_team_id=slot.home_youth_team_id,
                away_youth_team_id=slot.away_youth_team_id,
            )
            for slot in slots
        ]

        try:
            with transaction.atomic():
                Fixture.objects.bulk_create(fixtures)
                Match.objects.bulk_create(
                    [Match(fixture=fixture, status=MatchStatus.PENDING) for fixture in fixtures]
                )
        except IntegrityError as exc:
            raise FixtureIntegrityError(
                "Generated fixtures violated a database scheduling invariant."
            ) from exc

        generated_at = timezone.now()
        competition.status = LeagueCompetitionStatus.SCHEDULED
        competition.fixtures_generated_at = generated_at
        competition.save(
            update_fields=["status", "fixtures_generated_at", "updated_at"]
        )

        LeagueFixtureGenerationService._verify_existing_schedule(competition)
        return competition

    @staticmethod
    def _verify_existing_schedule(competition):
        fixture_count = Fixture.objects.filter(competition=competition).count()
        match_count = Match.objects.filter(fixture__competition=competition).count()
        if fixture_count != LEAGUE_FIXTURE_COUNT or match_count != LEAGUE_FIXTURE_COUNT:
            raise FixtureIntegrityError(
                "Persisted competition schedule is incomplete or corrupted."
            )


class MatchSchedulingService:
    @staticmethod
    @transaction.atomic
    def schedule(
        *, match_id, scheduled_at, record_revision=True, allow_reschedule=False,
        governance_authorized=False, revision_reason=None, revision_reason_text=None,
        revision_timezone_name=None
    ):
        source = lock_competition_source_and_match(match_id)
        match = source.match
        season = source.season
        if season is None:
            raise MatchNotSchedulableError(
                "Competition must be attached to a Season before scheduling matches."
            )
        scheduled_at = validate_kickoff(scheduled_at, season=season)

        if match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            raise MatchNotSchedulableError(
                "Only PENDING or SCHEDULED matches can receive a kickoff time."
            )
        if not competition_is_schedulable(source):
            raise MatchNotSchedulableError(
                "Competition is not in a schedulable state."
            )
        previous = match.scheduled_at
        is_reschedule = (
            match.status == MatchStatus.SCHEDULED
            and previous is not None
            and previous != scheduled_at
        )
        if is_reschedule and not allow_reschedule:
            raise MatchNotSchedulableError(
                "A scheduled kickoff can only change through the controlled reschedule service."
            )
        if is_reschedule and source.kind == "FEDERATION" and not governance_authorized:
            from competition_calendar_governance.exceptions import CompetitionCalendarGovernanceError
            from competition_calendar_governance.services import CompetitionCalendarGovernanceService
            try:
                CompetitionCalendarGovernanceService.assert_direct_reschedule_allowed(match=match)
            except CompetitionCalendarGovernanceError as exc:
                raise MatchNotSchedulableError(str(exc)) from exc

        match.scheduled_at = scheduled_at
        match.status = MatchStatus.SCHEDULED
        match.save(update_fields=["scheduled_at", "status", "updated_at"])

        if record_revision and previous != scheduled_at:
            # Generic scheduling paths remain auditable even when they predate
            # the calendar-aware engine. Calendar scheduling supplies richer
            # evidence itself and disables this generic revision.
            import hashlib
            import json
            from .constants import MatchScheduleReason
            from .models import MatchScheduleRevision
            from .scheduling_policy import KickoffSchedulingPolicyV1

            revision_number = MatchScheduleRevision.objects.filter(match=match).count() + 1
            tz_name = revision_timezone_name or getattr(scheduled_at.tzinfo, "key", None) or str(scheduled_at.tzinfo or "UTC")
            revision_reason = revision_reason or MatchScheduleReason.INITIAL
            revision_reason_text = revision_reason_text or "Direct authoritative Match scheduling service assignment."
            payload = {
                "match_id": str(match.pk),
                "revision_number": revision_number,
                "calendar_slot_id": None,
                "previous_scheduled_at": previous.isoformat() if previous else None,
                "scheduled_at": scheduled_at.isoformat(),
                "timezone_name": tz_name,
                "reason": revision_reason,
                "reason_text": revision_reason_text,
                "policy_key": KickoffSchedulingPolicyV1.policy_key,
                "policy_version": KickoffSchedulingPolicyV1.policy_version,
                "schema_version": KickoffSchedulingPolicyV1.schema_version,
            }
            evidence_hash = hashlib.sha256(
                json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
            ).hexdigest()
            MatchScheduleRevision.objects.create(
                match=match,
                revision_number=revision_number,
                previous_scheduled_at=previous,
                scheduled_at=scheduled_at,
                timezone_name=tz_name,
                reason=revision_reason,
                reason_text=revision_reason_text,
                policy_key=KickoffSchedulingPolicyV1.policy_key,
                policy_version=KickoffSchedulingPolicyV1.policy_version,
                schema_version=KickoffSchedulingPolicyV1.schema_version,
                evidence_hash=evidence_hash,
            )
        return match

    @staticmethod
    @transaction.atomic
    def cancel(*, match_id):
        source = lock_competition_source_and_match(match_id)
        match = source.match
        if match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            raise MatchNotCancellableError(
                "Only PENDING or SCHEDULED matches can be cancelled."
            )

        match.status = MatchStatus.CANCELLED
        match.cancelled_at = timezone.now()
        match.save(update_fields=["status", "cancelled_at", "updated_at"])
        # Matchday workers will also reconcile this state, but update and
        # audit the operational aggregate immediately when one exists.
        from .matchday import MatchdayOperationsService
        MatchdayOperationsService.mark_cancelled(match=match)
        from .interactive import InteractiveMatchRunnerService
        InteractiveMatchRunnerService.abort_for_match(match=match)
        return match

    @staticmethod
    def _lock_match(match_id):
        try:
            return (
                Match.objects.select_for_update(of=("self", "fixture"))
                .select_related(
                    "fixture",
                    "fixture__competition",
                    "fixture__competition__season",
                )
                .get(pk=match_id)
            )
        except Match.DoesNotExist as exc:
            raise MatchNotFoundError("Match does not exist.") from exc


class MatchLifecycleService:
    @staticmethod
    @transaction.atomic
    def start(*, match_id):
        source = lock_competition_source_and_match(match_id)
        competition, match = source.competition, source.match
        season = source.season

        if season is None or season.status != SeasonStatus.ACTIVE:
            raise MatchNotStartableError(
                "A match can only start while its Season is ACTIVE."
            )
        if not competition_is_startable(source):
            raise MatchNotStartableError("Competition is not active for match play.")
        if source.kind == "FEDERATION":
            from competition_draw_governance.exceptions import CompetitionDrawGovernanceError
            from competition_draw_governance.services import CompetitionDrawGovernanceService
            try:
                CompetitionDrawGovernanceService.assert_match_start_allowed(
                    competition=competition, fixture_generation=match.fixture.draw_generation
                )
            except CompetitionDrawGovernanceError as exc:
                raise MatchNotStartableError(str(exc)) from exc
            from competition_calendar_governance.exceptions import CompetitionCalendarGovernanceError
            from competition_calendar_governance.services import CompetitionCalendarGovernanceService
            try:
                CompetitionCalendarGovernanceService.assert_match_start_allowed(match=match)
            except CompetitionCalendarGovernanceError as exc:
                raise MatchNotStartableError(str(exc)) from exc
            from match_officials_governance.exceptions import MatchOfficialsGovernanceError
            from match_officials_governance.services import MatchOfficialsAppointmentService
            try:
                MatchOfficialsAppointmentService.assert_match_start_allowed(match=match)
            except MatchOfficialsGovernanceError as exc:
                raise MatchNotStartableError(str(exc)) from exc
        if match.status != MatchStatus.SCHEDULED:
            raise MatchNotStartableError("Only a SCHEDULED match can start.")

        from clubs.models import Club
        list(Club.objects.select_for_update(no_key=True).filter(pk__in=[match.fixture.home_club_id, match.fixture.away_club_id]).order_by("pk"))
        if source.kind == "LEAGUE" and match.fixture.competition_type == "ADULT":
            from clubs.models import ClubLeagueEntryRequest
            for club_id in (match.fixture.home_club_id, match.fixture.away_club_id):
                if not ClubLeagueEntryRequest.objects.filter(club_id=club_id, league_id=competition.league_id, season=season, status="APPROVED", payment__isnull=False).exists():
                    raise MatchNotStartableError("Both clubs must pay the season league entry fee with federation approval before kickoff.")
        from clubs.operations import stadium_for
        for club in (match.fixture.home_club, match.fixture.away_club):
            if stadium_for(club) is None:
                raise MatchNotStartableError("Both clubs require an active owned or leased stadium before kickoff.")

        from clubs.stadium_management import reserve_match
        from rest_framework.exceptions import ValidationError as VenueValidationError
        try:
            reserve_match(match)
        except VenueValidationError as exc:
            raise MatchNotStartableError(str(exc.detail)) from exc

        # Exact-calendar matches own a MatchdayOperation. Legacy/unit-test paths
        # without one preserve the original lifecycle semantics.
        from .matchday import MatchdayOperationsService
        MatchdayOperationsService.assert_match_start_ready(match=match)

        # A match cannot enter execution without authoritative configuration
        # for both fixture clubs. This revalidates current roster membership
        # and atomically freezes the two submitted lineups.
        from .lineups import MatchLineupService

        locked_lineups = MatchLineupService.lock_for_match_start(match=match)

        # Capture immutable kickoff-time engine input inside the same
        # transaction. If snapshot creation fails, lineup locks/status and the
        # match start transition roll back together.
        from .simulation import MatchSimulationSnapshotService

        snapshot = MatchSimulationSnapshotService.create_for_match_start(
            match=match,
            lineups=locked_lineups,
        )

        # INTERACTIVE matches open their server-owned checkpoint session in the
        # same kickoff transaction as the immutable simulation snapshot.
        from .interactive import InteractiveMatchRunnerService
        InteractiveMatchRunnerService.activate_for_match_start(
            match=match, snapshot=snapshot
        )

        now = timezone.now()
        mark_started_if_needed(source, now=now)

        match.status = MatchStatus.IN_PROGRESS
        match.started_at = now
        match.save(update_fields=["status", "started_at", "updated_at"])
        MatchdayOperationsService.mark_started(match=match)
        return match

    @staticmethod
    @transaction.atomic
    def complete(*, match_id, home_score, away_score):
        source = lock_competition_source_and_match(match_id)
        match = source.match
        if match.status != MatchStatus.IN_PROGRESS:
            raise MatchNotCompletableError(
                "Only an IN_PROGRESS match can be completed."
            )

        home_score = validate_score(home_score, field_name="home_score")
        away_score = validate_score(away_score, field_name="away_score")

        # Every match started by the current domain owns an immutable kickoff
        # simulation snapshot. Completing it here would create a score without
        # the matching authoritative report/events/statistics. Keep one write
        # path: MatchSimulationService persists score + report atomically.
        if hasattr(match, "simulation_snapshot"):
            raise MatchNotCompletableError(
                "Snapshot-backed matches must be completed through "
                "MatchSimulationService so score, events and statistics stay atomic."
            )

        match.home_score = home_score
        match.away_score = away_score
        match.completed_at = timezone.now()
        match.status = MatchStatus.COMPLETED
        match.result_type = MatchResultType.PLAYED
        match.save(
            update_fields=[
                "home_score",
                "away_score",
                "completed_at",
                "status",
                "result_type",
                "updated_at",
            ]
        )
        return match


class LeagueCompetitionLifecycleService:
    @staticmethod
    @transaction.atomic
    def complete(*, competition_id):
        try:
            competition = (
                LeagueCompetition.objects.select_for_update()
                .select_related("season", "league")
                .get(pk=competition_id)
            )
        except LeagueCompetition.DoesNotExist as exc:
            raise CompetitionNotCompletableError(
                "League competition does not exist."
            ) from exc

        if competition.status != LeagueCompetitionStatus.ACTIVE:
            raise CompetitionNotCompletableError(
                "Only an ACTIVE competition can be completed."
            )

        matches = Match.objects.filter(fixture__competition=competition)
        if matches.count() != LEAGUE_FIXTURE_COUNT:
            raise CompetitionNotCompletableError(
                "Competition does not contain the complete league schedule."
            )
        if matches.exclude(status=MatchStatus.COMPLETED).exists():
            raise CompetitionNotCompletableError(
                "Every league match must be COMPLETED first."
            )

        # Finalize immutable standings evidence from the authoritative results
        # before closing the competition. If standings finalization fails, the
        # entire completion transaction rolls back and the competition remains
        # ACTIVE.
        from leagues.standings_services import LeagueStandingsService

        LeagueStandingsService.finalize(competition_id=competition.pk)

        competition.status = LeagueCompetitionStatus.COMPLETED
        competition.completed_at = timezone.now()
        competition.save(update_fields=["status", "completed_at", "updated_at"])
        return competition
