"""Calendar-window -> exact kickoff scheduling and controlled rescheduling."""
from __future__ import annotations

import hashlib
import json
from datetime import time

from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from federations.constants import CompetitionKind, CompetitionScope
from leagues.constants import LeagueCompetitionType
from seasons.constants import SeasonCalendarPhase, SeasonCalendarSourceType
from seasons.models import SeasonCompetitionCalendarSlot

from .constants import MatchScheduleReason, MatchStatus
from .exceptions import (
    MatchRescheduleNotAllowedError,
    MatchSchedulingConfigurationError,
    MatchSchedulingConflictError,
)
from .models import (
    ClubHomeStadium,
    CountrySchedulingProfile,
    Match,
    MatchScheduleRevision,
)
from .scheduling_policy import KickoffSchedulingPolicyV1
from .services import MatchSchedulingService


def _sha256(payload: dict) -> str:
    raw = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()


class CompetitionKickoffSchedulingService:
    """Assign exact kickoffs to persisted Matches from immutable calendar slots."""

    @classmethod
    def schedule_season(cls, *, season_id, performed_by=None) -> dict:
        from seasons.models import Season

        season = Season.objects.get(pk=season_id)
        matches = list(
            Match.objects.select_related(
                "fixture",
                "fixture__home_club",
                "fixture__competition",
                "fixture__competition__league",
                "fixture__federation_competition",
                "fixture__federation_competition__federation",
            )
            .filter(
                Q(fixture__competition__season=season)
                | Q(fixture__federation_competition__season=season)
            )
            .order_by("fixture__round_number", "id")
        )
        scheduled = 0
        verified = 0
        for match in sorted(matches, key=cls._match_sort_key):
            before = match.scheduled_at
            cls.schedule_match_from_calendar(match_id=match.pk, performed_by=performed_by)
            if before is None:
                scheduled += 1
            else:
                verified += 1
        return {
            "season_id": str(season.pk),
            "match_count": len(matches),
            "scheduled_count": scheduled,
            "verified_count": verified,
        }

    @classmethod
    @transaction.atomic
    def schedule_match_from_calendar(
        cls,
        *,
        match_id,
        performed_by=None,
        reason=MatchScheduleReason.INITIAL,
    ) -> Match:
        match = (
            Match.objects.select_for_update(of=("self",))
            .select_related(
                "fixture",
                "fixture__home_club",
                "fixture__competition",
                "fixture__competition__league",
                "fixture__federation_competition",
                "fixture__federation_competition__federation",
            )
            .get(pk=match_id)
        )
        if match.status not in {MatchStatus.PENDING, MatchStatus.SCHEDULED}:
            raise MatchRescheduleNotAllowedError(
                "Only PENDING or SCHEDULED matches may be assigned from the calendar."
            )

        slot = cls._calendar_slot_for_match(match)
        profile, stadium, timezone_name, kickoff_time = cls._configuration_for_match(match)
        candidate = cls._find_candidate(
            match=match,
            slot=slot,
            profile=profile,
            timezone_name=timezone_name,
            kickoff_time=kickoff_time,
        )

        if match.scheduled_at is not None and match.scheduled_at == candidate:
            latest = match.schedule_revisions.order_by("-revision_number").first()
            if latest is not None and latest.scheduled_at == candidate and latest.calendar_slot_id == slot.pk:
                from .matchday import MatchdayOperationsService
                MatchdayOperationsService.refresh_for_match_schedule(
                    match_id=match.pk, performed_by=performed_by
                )
                return match
            cls._record_revision(
                match=match,
                previous=match.scheduled_at,
                slot=slot,
                timezone_name=timezone_name,
                reason=reason,
                reason_text="Calendar binding recorded for an already identical kickoff.",
                performed_by=performed_by,
            )
            from .matchday import MatchdayOperationsService
            MatchdayOperationsService.refresh_for_match_schedule(
                match_id=match.pk, performed_by=performed_by
            )
            return match

        actual_reason = reason
        anchor_kickoff = KickoffSchedulingPolicyV1.local_to_utc(
            local_date=slot.scheduled_date,
            local_time=kickoff_time,
            timezone_name=timezone_name,
        )
        if candidate != anchor_kickoff and reason == MatchScheduleReason.INITIAL:
            actual_reason = MatchScheduleReason.CONFLICT_SHIFT

        previous = match.scheduled_at
        match = MatchSchedulingService.schedule(match_id=match.pk, scheduled_at=candidate, record_revision=False, allow_reschedule=True)
        cls._record_revision(
            match=match,
            previous=previous,
            slot=slot,
            timezone_name=timezone_name,
            reason=actual_reason,
            reason_text=(
                "Deterministic conflict-safe calendar assignment."
                if actual_reason == MatchScheduleReason.CONFLICT_SHIFT
                else "Deterministic calendar assignment."
            ),
            performed_by=performed_by,
        )
        from .matchday import MatchdayOperationsService
        MatchdayOperationsService.refresh_for_match_schedule(
            match_id=match.pk, performed_by=performed_by
        )
        return match

    @classmethod
    @transaction.atomic
    def reschedule(
        cls,
        *,
        match_id,
        local_date,
        local_time: time,
        timezone_name: str | None = None,
        reason_text: str,
        performed_by=None,
    ) -> Match:
        match = (
            Match.objects.select_for_update(of=("self",))
            .select_related(
                "fixture", "fixture__home_club", "fixture__competition",
                "fixture__competition__league", "fixture__federation_competition",
            )
            .get(pk=match_id)
        )
        if match.status != MatchStatus.SCHEDULED:
            raise MatchRescheduleNotAllowedError("Only a SCHEDULED match may be rescheduled.")
        if not (reason_text or "").strip():
            raise MatchRescheduleNotAllowedError("Manual reschedule requires a reason.")

        profile, stadium, resolved_tz, _ = cls._configuration_for_match(match)
        timezone_name = timezone_name or resolved_tz
        try:
            candidate = KickoffSchedulingPolicyV1.local_to_utc(
                local_date=local_date, local_time=local_time, timezone_name=timezone_name
            )
        except ValueError as exc:
            raise MatchSchedulingConfigurationError(str(exc)) from exc
        cls._ensure_no_conflict(match=match, candidate=candidate, min_rest_hours=profile.min_rest_hours)
        previous = match.scheduled_at
        match = MatchSchedulingService.schedule(match_id=match.pk, scheduled_at=candidate, record_revision=False, allow_reschedule=True)
        cls._record_revision(
            match=match,
            previous=previous,
            slot=cls._calendar_slot_for_match(match),
            timezone_name=timezone_name,
            reason=MatchScheduleReason.MANUAL,
            reason_text=reason_text.strip(),
            performed_by=performed_by,
        )
        from .matchday import MatchdayOperationsService
        MatchdayOperationsService.refresh_for_match_schedule(
            match_id=match.pk, performed_by=performed_by
        )
        return match

    @classmethod
    def schedule_progressed_fixture(cls, *, fixture_id) -> Match | None:
        """Best-effort adapter for knockout fixtures created during progression.

        Configuration/calendar absence is intentionally non-fatal to tournament
        progression; operators can configure and run schedule_season later.
        Real scheduling conflicts, once configuration exists, remain explicit.
        """
        try:
            match = Match.objects.get(fixture_id=fixture_id)
            # A newly created knockout match may be the first available target
            # for suspension debt carried from the previous round.  Assign the
            # debt before matchday eligibility is prepared/scheduled.
            from .discipline import CompetitionDisciplineService
            CompetitionDisciplineService.sync_outstanding_for_match(match_id=match.pk)
            return cls.schedule_match_from_calendar(
                match_id=match.pk, reason=MatchScheduleReason.PROGRESSION
            )
        except (SeasonCompetitionCalendarSlot.DoesNotExist, MatchSchedulingConfigurationError):
            return None

    @classmethod
    def _match_sort_key(cls, match):
        fixture = match.fixture
        fed = fixture.federation_competition
        # Continental/global windows are least movable in practice, then cups,
        # then domestic leagues. UUID provides deterministic final ordering.
        if fed is not None and fed.scope == CompetitionScope.GLOBAL:
            priority = 0
        elif fed is not None:
            priority = 1
        else:
            priority = 2
        slot = cls._calendar_slot_for_match(match)
        return (slot.scheduled_date, priority, fixture.round_number, str(match.pk))

    @classmethod
    def _configuration_for_match(cls, match):
        home = match.fixture.home_club
        profile = CountrySchedulingProfile.objects.filter(
            country__iexact=home.country, is_active=True
        ).first()
        if profile is None:
            raise MatchSchedulingConfigurationError(
                f"No active CountrySchedulingProfile for {home.country!r}."
            )
        stadium = ClubHomeStadium.objects.filter(club=home, is_active=True).first()
        timezone_name = stadium.timezone_name if stadium and stadium.timezone_name else profile.timezone_name
        try:
            KickoffSchedulingPolicyV1.validate_timezone_name(timezone_name)
        except ValueError as exc:
            raise MatchSchedulingConfigurationError(str(exc)) from exc

        if stadium and stadium.kickoff_time_override:
            kickoff_time = stadium.kickoff_time_override
        else:
            fixture = match.fixture
            fed = fixture.federation_competition
            if fixture.competition_type == LeagueCompetitionType.YOUTH:
                kickoff_time = profile.youth_kickoff_time
            elif fed is not None and fed.scope == CompetitionScope.GLOBAL:
                kickoff_time = profile.continental_kickoff_time
            elif fed is not None:
                kickoff_time = profile.cup_kickoff_time
            else:
                kickoff_time = profile.adult_kickoff_time
        return profile, stadium, timezone_name, kickoff_time

    @classmethod
    def _find_candidate(cls, *, match, slot, profile, timezone_name, kickoff_time):
        season = match.fixture.season
        from seasons.models import SeasonAutomationPolicy
        policy = SeasonAutomationPolicy.objects.filter(season=season).first()
        if policy and match.fixture.competition_id:
            kickoff_time = policy.kickoff_time
        for candidate_date in KickoffSchedulingPolicyV1.candidate_dates(
            anchor_date=slot.scheduled_date,
            season_start=season.start_date,
            season_end=season.end_date,
            max_shift_days=profile.max_auto_shift_days,
        ):
            candidate = KickoffSchedulingPolicyV1.local_to_utc(
                local_date=candidate_date,
                local_time=kickoff_time,
                timezone_name=timezone_name,
            )
            if policy:
                if candidate < policy.starts_at:
                    continue
                if match.fixture.competition_id:
                    if policy.midseason_opens_at <= candidate < policy.midseason_closes_at:
                        continue
                    if match.fixture.round_number <= 19 and candidate >= policy.midseason_opens_at:
                        continue
                    if match.fixture.round_number > 19 and candidate < policy.midseason_closes_at:
                        continue
            try:
                cls._ensure_no_conflict(
                    match=match, candidate=candidate, min_rest_hours=profile.min_rest_hours
                )
            except MatchSchedulingConflictError:
                continue
            return candidate
        raise MatchSchedulingConflictError(
            f"No conflict-free kickoff found within ±{profile.max_auto_shift_days} days "
            f"of {slot.scheduled_date.isoformat()}."
        )

    @classmethod
    def _ensure_no_conflict(cls, *, match, candidate, min_rest_hours):
        start, end = KickoffSchedulingPolicyV1.rest_window(
            kickoff=candidate, min_rest_hours=min_rest_hours
        )
        club_ids = [match.fixture.home_club_id, match.fixture.away_club_id]
        conflict = (
            Match.objects.filter(
                status__in=[MatchStatus.SCHEDULED, MatchStatus.IN_PROGRESS, MatchStatus.COMPLETED],
                scheduled_at__gt=start,
                scheduled_at__lt=end,
            )
            .exclude(pk=match.pk)
            .filter(
                Q(fixture__home_club_id__in=club_ids)
                | Q(fixture__away_club_id__in=club_ids)
            )
            .order_by("scheduled_at")
            .first()
        )
        if conflict is not None:
            raise MatchSchedulingConflictError(
                f"Rest-window conflict with match {conflict.pk} at {conflict.scheduled_at}."
            )

    @classmethod
    def _calendar_slot_for_match(cls, match):
        fixture = match.fixture
        if fixture.competition_id:
            return SeasonCompetitionCalendarSlot.objects.get(
                season=fixture.competition.season,
                source_type=SeasonCalendarSourceType.LEAGUE,
                league_competition=fixture.competition,
                phase=SeasonCalendarPhase.LEAGUE_ROUND,
                sequence=fixture.round_number,
            )
        competition = fixture.federation_competition
        if hasattr(fixture, "federation_group_fixture"):
            phase = SeasonCalendarPhase.GROUP_MATCHDAY
            sequence = fixture.federation_group_fixture.matchday
        else:
            phase = SeasonCalendarPhase.KNOCKOUT_ROUND
            sequence = fixture.round_number - 6 if fixture.round_number > 6 else fixture.round_number
        return SeasonCompetitionCalendarSlot.objects.get(
            season=competition.season,
            source_type=SeasonCalendarSourceType.FEDERATION,
            federation_competition=competition,
            phase=phase,
            sequence=sequence,
        )

    @classmethod
    def _record_revision(
        cls, *, match, previous, slot, timezone_name, reason, reason_text, performed_by
    ):
        revision_number = match.schedule_revisions.count() + 1
        payload = {
            "match_id": str(match.pk),
            "revision_number": revision_number,
            "calendar_slot_id": str(slot.pk) if slot else None,
            "previous_scheduled_at": previous.isoformat() if previous else None,
            "scheduled_at": match.scheduled_at.isoformat(),
            "timezone_name": timezone_name,
            "reason": reason,
            "reason_text": reason_text,
            "policy_key": KickoffSchedulingPolicyV1.policy_key,
            "policy_version": KickoffSchedulingPolicyV1.policy_version,
            "schema_version": KickoffSchedulingPolicyV1.schema_version,
        }
        MatchScheduleRevision.objects.create(
            match=match,
            revision_number=revision_number,
            calendar_slot=slot,
            previous_scheduled_at=previous,
            scheduled_at=match.scheduled_at,
            timezone_name=timezone_name,
            reason=reason,
            reason_text=reason_text,
            policy_key=KickoffSchedulingPolicyV1.policy_key,
            policy_version=KickoffSchedulingPolicyV1.policy_version,
            schema_version=KickoffSchedulingPolicyV1.schema_version,
            evidence_hash=_sha256(payload),
            performed_by=performed_by,
        )

    @classmethod
    def _verify_latest_revision(cls, *, match, expected):
        latest = match.schedule_revisions.order_by("-revision_number").first()
        if latest is None or latest.scheduled_at != expected:
            raise MatchSchedulingConflictError(
                "Scheduled Match is missing matching immutable schedule evidence."
            )
