from datetime import date, datetime, timedelta

from django.db import IntegrityError, transaction
from django.utils import timezone

from clubs.models import ClubStatus

from .constants import ContractOfferInitiatorRole, ContractRosterScope, ContractStatus, ContractTerminationReason, OfferStatus
from .exceptions import (
    ClubCannotOfferContractError,
    ContractNotActiveError,
    ContractNotExpiredYetError,
    ContractNotFoundError,
    ContractRosterIntegrationError,
    InactiveContractCareerError,
    InvalidContractDatesError,
    InvalidContractOfferError,
    OfferAlreadyAcceptedError,
    OfferExpiredError,
    OfferNotFoundError,
    OfferNotPendingError,
    PlayerAlreadyContractedError,
)
from .models import Contract, ContractOffer
from .financial import ContractFinancialService
from .roster import ContractRosterIntegrationService
from .validators import (
    validate_contract_dates,
    validate_money,
    validate_offer_dates,
    validate_positive_duration,
    validate_termination_reason,
)


def _emit_contract_offer_event(offer, event_type, payload=None):
    from core_runtime.services import OutboxService
    return OutboxService.enqueue(
        topic="contracts", event_type=event_type, aggregate_type="ContractOffer", aggregate_id=offer.pk,
        deduplication_key=f"contract-offer:{offer.pk}:{event_type}:{offer.status}",
        payload={
            "offer_id": str(offer.pk), "player_id": str(offer.player_id), "club_id": str(offer.club_id),
            "status": offer.status, "initiator_role": offer.initiator_role, **(payload or {}),
        },
    )


def _emit_contract_lifecycle_event(contract, event_type, payload=None):
    from core_runtime.services import OutboxService
    return OutboxService.enqueue(
        topic="contracts", event_type=event_type, aggregate_type="CONTRACT", aggregate_id=contract.pk,
        deduplication_key=f"contract:{contract.pk}:{event_type}:{contract.status}",
        payload={"contract_id": str(contract.pk), "status": contract.status, **(payload or {})},
    )


class ContractOfferService:
    @staticmethod
    @transaction.atomic
    def create_offer(
        *,
        player,
        club,
        salary,
        duration_months,
        expires_at,
        signing_bonus=0,
        transfer_fee=0,
        release_clause=None,
        squad_scope=ContractRosterScope.SENIOR,
        initiator_role=ContractOfferInitiatorRole.SYSTEM,
        initiated_by=None,
        compensation_frequency=None,
        compensation_custom_interval_days=None,
        first_payment_delay_days=0,
        clauses=None,
    ):
        if squad_scope not in ContractRosterScope.values:
            raise InvalidContractOfferError("Invalid contract squad scope.")
        player, club = _lock_active_participants(player.pk, club.pk)

        if initiator_role not in ContractOfferInitiatorRole.values:
            raise InvalidContractOfferError("Invalid contract-offer initiator role.")
        if initiator_role == ContractOfferInitiatorRole.PLAYER:
            if initiated_by is None or player.career.user_id != initiated_by.pk:
                raise InvalidContractOfferError("PLAYER offer must be initiated by the player owner.")
        elif initiator_role == ContractOfferInitiatorRole.CLUB:
            from clubs.access import can_manage_club
            if initiated_by is None or not can_manage_club(initiated_by, club):
                raise InvalidContractOfferError("CLUB offer must be initiated by club management.")
        elif initiated_by is not None:
            raise InvalidContractOfferError("SYSTEM offer cannot carry a user initiator.")

        validate_positive_duration(duration_months)
        from players.age import sporting_age
        maximum = 36 if sporting_age(player) < 18 else 60
        if duration_months > maximum:
            raise InvalidContractOfferError(f"Contract duration exceeds {maximum} months.")
        compensation_frequency = compensation_frequency or "MONTHLY"
        if compensation_frequency is not None:
            from .constants import ContractCompensationFrequency
            if compensation_frequency not in ContractCompensationFrequency.values:
                raise InvalidContractOfferError("Invalid compensation frequency.")
            if compensation_frequency == ContractCompensationFrequency.CUSTOM:
                if not compensation_custom_interval_days or int(compensation_custom_interval_days) < 1:
                    raise InvalidContractOfferError("CUSTOM compensation frequency requires compensation_custom_interval_days >= 1.")
            else:
                compensation_custom_interval_days = None
        if first_payment_delay_days is None or int(first_payment_delay_days) < 0:
            raise InvalidContractOfferError("first_payment_delay_days must be non-negative.")
        if clauses is not None and not isinstance(clauses, list):
            raise InvalidContractOfferError("clauses must be a list.")

        salary = validate_money(salary, "salary")
        signing_bonus = validate_money(signing_bonus, "signing_bonus")
        transfer_fee = validate_money(transfer_fee, "transfer_fee")
        release_clause = validate_money(release_clause, "release_clause")
        if release_clause <= 0:
            raise InvalidContractOfferError("A positive release clause is mandatory.")
        if salary <= 0:
            raise InvalidContractOfferError("Salary installment must be positive.")

        validate_offer_dates(
            expires_at=expires_at,
            now=timezone.now(),
        )

        if Contract.objects.filter(
            player=player,
            status=ContractStatus.ACTIVE,
        ).exists():
            raise PlayerAlreadyContractedError(
                "Player already has an active contract."
            )

        from transfers.recruitment import assert_recruitment
        assert_recruitment(club=club, player=player)

        try:
            offer = ContractOffer.objects.create(
                player=player,
                club=club,
                squad_scope=squad_scope,
                status=OfferStatus.PENDING,
                initiator_role=initiator_role,
                created_by=initiated_by,
                salary=salary,
                signing_bonus=signing_bonus,
                transfer_fee=transfer_fee,
                release_clause=release_clause,
                terms_version=2,
                compensation_frequency=compensation_frequency,
                compensation_custom_interval_days=compensation_custom_interval_days,
                first_payment_delay_days=first_payment_delay_days or 0,
                clauses=clauses or [],
                duration_months=duration_months,
                expires_at=expires_at,
            )
            _emit_contract_offer_event(offer, "contract.offer.created")
            return offer
        except IntegrityError as exc:
            raise InvalidContractOfferError(
                "The contract offer violates a database invariant."
            ) from exc

    @staticmethod
    @transaction.atomic
    def withdraw_offer(*, offer_id):
        offer = _lock_offer(offer_id)

        if offer.status != OfferStatus.PENDING:
            raise OfferNotPendingError(
                "Only pending offers can be withdrawn."
            )

        offer.status = OfferStatus.WITHDRAWN
        offer.responded_at = timezone.now()
        offer.rejection_reason = ""
        offer.save(
            update_fields=[
                "status",
                "responded_at",
                "rejection_reason",
                "updated_at",
            ]
        )
        _emit_contract_offer_event(offer, "contract.offer.withdrawn")
        return offer

    @staticmethod
    @transaction.atomic
    def reject_offer(*, offer_id, reason=""):
        offer = _lock_offer(offer_id)

        if offer.status != OfferStatus.PENDING:
            raise OfferNotPendingError(
                "Only pending offers can be rejected."
            )

        if not isinstance(reason, str):
            raise InvalidContractOfferError(
                "Rejection reason must be text."
            )

        reason = reason.strip()
        if len(reason) > 255:
            raise InvalidContractOfferError(
                "Rejection reason cannot exceed 255 characters."
            )

        offer.status = OfferStatus.REJECTED
        offer.responded_at = timezone.now()
        offer.rejection_reason = reason
        offer.save(
            update_fields=[
                "status",
                "responded_at",
                "rejection_reason",
                "updated_at",
            ]
        )
        _emit_contract_offer_event(offer, "contract.offer.rejected", {"reason": reason})
        return offer


class ContractAcceptanceService:
    @staticmethod
    def accept_offer(*, offer_id, start_date=None):
        """
        Accept one pending offer atomically.

        Lock order is intentionally:

            Club -> Player -> Offer

        This matches the participant lock order used by offer creation and
        avoids the deadlock pattern created by locking two competing offers
        before serializing on their shared Player row.
        """
        expired = False
        contract = None

        with transaction.atomic():
            try:
                offer_identity = (
                    ContractOffer.objects
                    .values("player_id", "club_id")
                    .get(pk=offer_id)
                )
            except ContractOffer.DoesNotExist as exc:
                raise OfferNotFoundError(
                    "Offer does not exist."
                ) from exc

            player, club = _lock_active_participants(
                offer_identity["player_id"],
                offer_identity["club_id"],
            )

            offer = _lock_offer(offer_id)

            if (
                offer.player_id != player.pk
                or offer.club_id != club.pk
            ):
                raise InvalidContractOfferError(
                    "Offer participants changed during acceptance."
                )

            if offer.status == OfferStatus.ACCEPTED:
                raise OfferAlreadyAcceptedError(
                    "Offer is already accepted."
                )

            if offer.status != OfferStatus.PENDING:
                raise OfferNotPendingError(
                    "Only pending offers can be accepted."
                )

            now = timezone.now()

            # Persist expiration before raising. Raising inside this atomic
            # block would roll the EXPIRED state back.
            if offer.expires_at <= now:
                offer.status = OfferStatus.EXPIRED
                offer.responded_at = now
                offer.rejection_reason = ""
                offer.save(
                    update_fields=[
                        "status",
                        "responded_at",
                        "rejection_reason",
                        "updated_at",
                    ]
                )
                expired = True

            else:
                from transfers.recruitment import assert_recruitment
                assert_recruitment(club=club, player=player, now=now)
                if Contract.objects.filter(
                    player=player,
                    status=ContractStatus.ACTIVE,
                ).exists():
                    raise PlayerAlreadyContractedError(
                        "Player already has an active contract."
                    )

                if offer.release_clause is None or offer.release_clause <= 0:
                    raise InvalidContractOfferError("A positive release clause must be agreed before acceptance.")

                effective_start_date = (
                    start_date
                    if start_date is not None
                    else timezone.localdate()
                )

                if (
                    not isinstance(effective_start_date, date)
                    or isinstance(effective_start_date, datetime)
                ):
                    raise InvalidContractDatesError(
                        "Contract start date must be a date."
                    )

                end_date = _add_months(
                    effective_start_date,
                    offer.duration_months,
                )

                validate_contract_dates(
                    start_date=effective_start_date,
                    end_date=end_date,
                )

                offer.status = OfferStatus.ACCEPTED
                offer.responded_at = now
                offer.rejection_reason = ""
                offer.save(
                    update_fields=[
                        "status",
                        "responded_at",
                        "rejection_reason",
                        "updated_at",
                    ]
                )

                (
                    ContractOffer.objects
                    .filter(
                        player_id=player.pk,
                        status=OfferStatus.PENDING,
                    )
                    .exclude(pk=offer.pk)
                    .update(
                        status=OfferStatus.REJECTED,
                        responded_at=now,
                        rejection_reason="Another offer was accepted.",
                        updated_at=now,
                    )
                )

                try:
                    contract = Contract.objects.create(
                        player=player,
                        club=club,
                        source_offer=offer,
                        squad_scope=offer.squad_scope,
                        status=ContractStatus.ACTIVE,
                        salary=offer.salary,
                        signing_bonus=offer.signing_bonus,
                        transfer_fee=offer.transfer_fee,
                        release_clause=offer.release_clause,
                        terms_version=offer.terms_version,
                        season_months_remaining=offer.duration_months if offer.terms_version >= 2 else None,
                        start_date=effective_start_date,
                        end_date=end_date,
                    )
                except IntegrityError as exc:
                    raise PlayerAlreadyContractedError(
                        "Player already has an active contract."
                    ) from exc

                # Register current club membership before financial settlement.
                # Both operations remain inside this outer transaction; any
                # roster or financial failure rolls the Contract, Offer states,
                # roster row and Ledger/Wallet changes back together.
                ContractRosterIntegrationService.register_contract(
                    contract=contract,
                )

                # Financial settlement remains the final external state change.
                ContractFinancialService.settle_signing_bonus(
                    contract=contract,
                )

                # Explicit compensation cadence and negotiated clauses become
                # versioned contract terms only after the offer is accepted.
                from .terms import ContractTermsService
                if offer.compensation_frequency:
                    from economy.services import WalletService
                    WalletService.get_or_create_player_wallet(player=player)
                ContractTermsService.materialize_from_offer(contract=contract)
                _emit_contract_offer_event(offer, "contract.offer.accepted", {"contract_id": str(contract.pk)})
                _emit_contract_lifecycle_event(contract, "contract.activated", {"offer_id": str(offer.pk)})

        if expired:
            raise OfferExpiredError(
                "Offer has expired."
            )

        return contract


class ContractLifecycleService:
    @staticmethod
    @transaction.atomic
    def terminate_contract(
        *,
        contract_id,
        reason,
        terminated_at=None,
        maximum_payment=None,
    ):
        contract = _lock_contract_with_participants(contract_id)

        if contract.status != ContractStatus.ACTIVE:
            raise ContractNotActiveError(
                "Only an active contract can be terminated."
            )

        from player_loans.constants import PlayerLoanStatus
        from player_loans.models import PlayerLoan
        if PlayerLoan.objects.select_for_update().filter(
            parent_contract=contract,
            status__in=[PlayerLoanStatus.PENDING_APPROVAL, PlayerLoanStatus.APPROVED, PlayerLoanStatus.ACTIVE],
        ).exists():
            raise ContractRosterIntegrationError(
                "Parent contract cannot terminate while a player-loan workflow is open."
            )

        reason = validate_termination_reason(reason)
        effective_terminated_at = terminated_at or timezone.now()

        if not isinstance(effective_terminated_at, datetime):
            raise InvalidContractDatesError(
                "Termination time must be a datetime."
            )
        if timezone.is_naive(effective_terminated_at):
            raise InvalidContractDatesError(
                "Termination time must be timezone-aware."
            )
        if effective_terminated_at > timezone.now():
            raise InvalidContractDatesError(
                "Termination time cannot be in the future."
            )
        if effective_terminated_at.date() < contract.start_date:
            raise InvalidContractDatesError(
                "Termination time cannot be before contract start."
            )

        if reason == ContractTerminationReason.CLUB_DECISION:
            if terminated_at is not None:
                raise InvalidContractDatesError("Club-decision termination cannot be backdated.")
            from .termination import settle_club_termination
            settle_club_termination(contract=contract, maximum_payment=maximum_payment)

        contract.status = ContractStatus.TERMINATED
        contract.termination_reason = reason
        contract.terminated_at = effective_terminated_at
        contract.save(
            update_fields=[
                "status",
                "termination_reason",
                "terminated_at",
                "updated_at",
            ]
        )
        ContractRosterIntegrationService.remove_inactive_contract(
            contract=contract,
        )
        from .terms import ContractTermsService
        ContractTermsService.close_contract_terms(contract=contract, effective_date=effective_terminated_at.date())
        _emit_contract_lifecycle_event(contract, "contract.terminated", {"reason": reason})
        return contract

    @staticmethod
    @transaction.atomic
    def expire_contract(*, contract_id, season_cutoff=None):
        contract = _lock_contract_with_participants(contract_id)

        if contract.status != ContractStatus.ACTIVE:
            raise ContractNotActiveError(
                "Only an active contract can expire."
            )

        if season_cutoff is not None and (contract.season_months_remaining != 0 or season_cutoff < contract.start_date or season_cutoff > timezone.localdate()):
            raise InvalidContractDatesError("Invalid sporting-season expiration cutoff.")
        if season_cutoff is None and contract.end_date > timezone.localdate():
            raise ContractNotExpiredYetError(
                "Contract cannot expire before its end date."
            )
        from player_loans.constants import PlayerLoanStatus
        from player_loans.models import PlayerLoan
        if PlayerLoan.objects.select_for_update().filter(
            parent_contract=contract,
            status__in=[PlayerLoanStatus.PENDING_APPROVAL, PlayerLoanStatus.APPROVED, PlayerLoanStatus.ACTIVE],
        ).exists():
            raise ContractRosterIntegrationError(
                "Parent contract cannot expire while a player-loan workflow is open."
            )

        contract.status = ContractStatus.EXPIRED
        contract.termination_reason = ""
        contract.terminated_at = None
        contract.save(
            update_fields=[
                "status",
                "termination_reason",
                "terminated_at",
                "updated_at",
            ]
        )
        ContractRosterIntegrationService.remove_inactive_contract(
            contract=contract,
        )
        from .terms import ContractTermsService
        ContractTermsService.close_contract_terms(contract=contract, effective_date=season_cutoff or contract.end_date)
        _emit_contract_lifecycle_event(contract, "contract.expired")
        return contract


def _add_months(value, months):
    month_index = value.month - 1 + months
    year = value.year + month_index // 12
    month = month_index % 12 + 1

    if month == 12:
        next_month = date(year + 1, 1, 1)
    else:
        next_month = date(year, month + 1, 1)

    last_day = (next_month - timedelta(days=1)).day

    return date(
        year,
        month,
        min(value.day, last_day),
    )


def _lock_active_participants(player_id, club_id):
    from careers.models import CareerStatus
    from clubs.models import Club
    from players.models import Player

    try:
        club = (
            Club.objects
            .select_for_update()
            .get(pk=club_id)
        )
    except Club.DoesNotExist as exc:
        raise InvalidContractOfferError(
            "Club does not exist."
        ) from exc

    try:
        player = (
            Player.objects
            .select_for_update()
            .get(pk=player_id)
        )
    except Player.DoesNotExist as exc:
        raise InvalidContractOfferError(
            "Player does not exist."
        ) from exc

    if club.status != ClubStatus.ACTIVE:
        raise ClubCannotOfferContractError(
            "Only an ACTIVE club can sign a contract."
        )

    if (
        player.career.status != CareerStatus.ACTIVE
        or club.coach_career.status != CareerStatus.ACTIVE
    ):
        raise InactiveContractCareerError(
            "Player and coach careers must be active."
        )

    return player, club


def _lock_offer(offer_id):
    try:
        return (
            ContractOffer.objects
            .select_for_update()
            .get(pk=offer_id)
        )
    except ContractOffer.DoesNotExist as exc:
        raise OfferNotFoundError(
            "Offer does not exist."
        ) from exc


def _lock_contract_with_participants(contract_id):
    """Lock Club -> Player -> Contract for lifecycle/roster coordination."""
    from clubs.models import Club
    from players.models import Player

    try:
        identity = Contract.objects.values(
            "club_id",
            "player_id",
        ).get(pk=contract_id)
    except Contract.DoesNotExist as exc:
        raise ContractNotFoundError(
            "Contract does not exist."
        ) from exc

    Club.objects.select_for_update().get(pk=identity["club_id"])
    Player.objects.select_for_update().get(pk=identity["player_id"])

    try:
        return Contract.objects.select_for_update().get(pk=contract_id)
    except Contract.DoesNotExist as exc:
        raise ContractNotFoundError(
            "Contract does not exist."
        ) from exc


def _lock_contract(contract_id):
    try:
        return (
            Contract.objects
            .select_for_update()
            .get(pk=contract_id)
        )
    except Contract.DoesNotExist as exc:
        raise ContractNotFoundError(
            "Contract does not exist."
        ) from exc
