"""Negotiated exhibitions. Official fixture/engine implementations are unchanged."""
import secrets
from datetime import timedelta
from decimal import Decimal
from types import SimpleNamespace

from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from rest_framework.exceptions import PermissionDenied

from clubs.models import Club, ClubSquadMembership
from economy.constants import LedgerTransactionType as Tx, WalletType
from economy.models import Wallet
from economy.services import EconomyTransferService, WalletService
from economy.validators import validate_token_amount
from federations.access import can_control_federation
from .friendly_models import FriendlyGame, FriendlyAudit
from .engine.serialization import payload_sha256


class FriendlyError(Exception):
    pass


def manages(user, club):
    return bool(user and user.is_authenticated and user.is_active and
                user.pk in {club.owner_id, club.coach_user_id})


def _club_authority(user, club):
    if not manages(user, club):
        raise PermissionDenied("Club owner/coach authority required.")


def _participants(game):
    return list(Club.objects.select_for_update(of=("self",)).filter(pk__in=[game.home_club_id, game.away_club_id])
                .select_related("coach_career__user", "regional_federation").order_by("pk"))


def _independent(clubs):
    if len(clubs) != 2 or any(c.status != "ACTIVE" for c in clubs):
        raise FriendlyError("Two active distinct clubs are required.")
    ids = [{i for i in (c.owner_id, c.coach_user_id) if i is not None} for c in clubs]
    if ids[0].intersection(ids[1]):
        raise FriendlyError("Clubs under shared ownership or management cannot play funded friendlies.")


def _supervision_valid(game, clubs):
    from .friendly_supervision import validate_supervisor
    validate_supervisor(game, clubs)


def _governor(user, game, clubs):
    if not can_control_federation(user, game.federation):
        raise PermissionDenied("The supervising federation governor is required.")
    if any(manages(user, c) for c in clubs) or user.pk in {game.proposed_by_id, game.accepted_by_id}:
        raise PermissionDenied("A participant cannot approve or settle its own friendly.")
    from players.models import Player
    if Player.objects.filter(career__user=user, squad_membership__club_id__in=[c.pk for c in clubs]).exists():
        raise PermissionDenied("A participating player cannot supervise this friendly.")


def _audit(game, actor, action, **details):
    evidence = {"game_id": str(game.pk), "version": game.version, "status": game.status,
                "home_club_id": str(game.home_club_id), "away_club_id": str(game.away_club_id),
                "federation_id": str(game.federation_id), "currency": "FTG",
                "stake_per_club": str(game.stake), "kickoff": game.scheduled_at.isoformat(), **details}
    FriendlyAudit.objects.create(game=game, actor=actor, action=action, evidence=evidence,
                                evidence_hash=payload_sha256(evidence))


def _terms(stake, scheduled_at):
    if stake == 0 or str(stake) == "0":
        stake = Decimal("0")
    else:
        stake = validate_token_amount(stake)
    if timezone.is_naive(scheduled_at) or scheduled_at < timezone.now() + timedelta(minutes=15):
        raise FriendlyError("Kickoff must be timezone-aware and at least 15 minutes ahead.")
    return stake


def _no_conflict(game):
    from .models import Match
    ids = [game.home_club_id, game.away_club_id]
    start, end = game.scheduled_at - timedelta(hours=3), game.scheduled_at + timedelta(hours=3)
    if FriendlyGame.objects.exclude(pk=game.pk).filter(
        Q(home_club_id__in=ids) | Q(away_club_id__in=ids),
        status__in=["FUNDED", "APPROVED", "RUNNING"], scheduled_at__range=(start, end),
    ).exists() or Match.objects.filter(
        Q(fixture__home_club_id__in=ids) | Q(fixture__away_club_id__in=ids),
        status__in=["SCHEDULED", "IN_PROGRESS"], scheduled_at__range=(start, end),
    ).exists():
        raise FriendlyError("A club already has a match within the protected three-hour window.")


@transaction.atomic
def propose(*, user, home_club_id, away_club_id, stake, scheduled_at):
    clubs = list(Club.objects.select_for_update(of=("self",)).filter(pk__in=[home_club_id, away_club_id])
                 .select_related("coach_career__user", "regional_federation").order_by("pk"))
    _independent(clubs)
    home = next((c for c in clubs if str(c.pk) == str(home_club_id)), None)
    _club_authority(user, home)
    if any(manages(user, c) for c in clubs if c.pk != home.pk):
        raise PermissionDenied("A user cannot represent both participants.")
    from .friendly_supervision import choose_supervisor
    federation, allocation = choose_supervisor(clubs)
    stake = _terms(stake, scheduled_at)
    game = FriendlyGame.objects.create(home_club_id=home_club_id, away_club_id=away_club_id,
        federation=federation, offered_by_club_id=home_club_id, proposed_by=user, stake=stake, scheduled_at=scheduled_at)
    _audit(game, user, "PROPOSED", supervision_allocation=allocation)
    return game


@transaction.atomic
def negotiate(*, user, game_id, version, action, club_id=None, stake=None, scheduled_at=None):
    game = FriendlyGame.objects.select_for_update().get(pk=game_id)
    clubs = _participants(game)
    club = next((c for c in clubs if str(c.pk) == str(club_id)), None)
    if club is None:
        raise PermissionDenied("Participant club required.")
    _club_authority(user, club)
    if game.status != "PROPOSED" or game.version != version:
        raise FriendlyError("Offer changed or has already been processed; reload the current version.")
    if action == "withdraw":
        if club.pk != game.offered_by_club_id:
            raise PermissionDenied("Only the current proposer can withdraw the offer.")
        game.status = "DECLINED"
    elif action in {"counter", "accept", "decline"}:
        if club.pk == game.offered_by_club_id:
            raise PermissionDenied("The other club must respond to the latest offer.")
        _independent(clubs)
        offering = next(c for c in clubs if c.pk == game.offered_by_club_id)
        if not manages(game.proposed_by, offering):
            raise FriendlyError("Offering club authority changed; issue a new offer.")
        if action == "counter":
            game.stake = _terms(stake, scheduled_at)
            game.scheduled_at, game.offered_by_club, game.proposed_by = scheduled_at, club, user
            game.version += 1
        elif action == "decline":
            game.status = "DECLINED"
        else:
            _supervision_valid(game, clubs)
            _terms(game.stake, game.scheduled_at)
            _no_conflict(game)
            if game.stake > 0:
                escrow, _ = Wallet.objects.get_or_create(wallet_type=WalletType.FRIENDLY_ESCROW)
                wallets = {c.pk: WalletService.get_or_create_club_wallet(club=c) for c in clubs}
                WalletService.lock_wallets_canonically(wallets=[escrow, *wallets.values()])
                for side in ("home", "away"):
                    wallet = wallets[getattr(game, f"{side}_club_id")]
                    entry = EconomyTransferService.transfer(source_wallet=wallet, destination_wallet=escrow,
                        amount=game.stake, transaction_type=Tx.FRIENDLY_RESERVE,
                        reference_type="friendly_reserve", reference_id=str(game.pk),
                        idempotency_key=f"friendly:{game.pk}:reserve:{side}", description="امانت سهم بازی دوستانه؛ بدون پرداخت خودکار به برنده.")
                    setattr(game, f"{side}_reservation", entry)
            game.accepted_by = user
            game.status = "FUNDED" if game.stake else "APPROVED"
    else:
        raise FriendlyError("Unknown negotiation action.")
    game.save()
    _audit(game, user, action.upper())
    return game


@transaction.atomic
def approve(*, user, game_id, version, note):
    game = FriendlyGame.objects.select_for_update().get(pk=game_id)
    clubs = _participants(game)
    _governor(user, game, clubs)
    if game.status != "FUNDED" or game.version != version or not str(note).strip():
        raise FriendlyError("A funded current agreement and approval reason are required.")
    _independent(clubs)
    _supervision_valid(game, clubs)
    _terms(game.stake, game.scheduled_at)
    _no_conflict(game)
    game.status, game.approved_by = "APPROVED", user
    game.save()
    _audit(game, user, "APPROVED", note=note)
    return game


def _team(club, *, staff_effect=None):
    from players.models import Player
    from injuries.resolver import InjuryResolver
    from .default_lineups import DefaultLineupService
    from .lineups import _normalize_starters, _validate_slots_for_draft, _validate_required_position_compatibility
    from .constants import FORMATION_SLOTS
    from .engine.state import TeamState
    from .simulation import _player_state
    data = DefaultLineupService.get_for_club(club=club, match=object())
    if data.get("valid") is False:
        raise FriendlyError("Saved default squad is no longer valid.")
    rows = _normalize_starters(data["starters"])
    actual_slots = {r["slot"] for r in rows}
    allowed_slots = set(FORMATION_SLOTS.get(data["formation"], []))
    if len(rows) != 11 or len(actual_slots) != 11 or "GK" not in actual_slots or not actual_slots <= allowed_slots or (data["formation"] != "CUSTOM" and actual_slots != allowed_slots):
        raise FriendlyError("Both clubs need a complete valid default XI.")
    _validate_slots_for_draft(formation=data["formation"], starter_rows=rows)
    ids = [str(r["player_id"]) for r in rows] + [str(i) for i in data["substitutes"]]
    if len(ids) != 21 or len(set(ids)) != len(ids) or str(data["captain_id"]) not in ids[:11]:
        raise FriendlyError("Lineup contains duplicate players or an invalid captain.")
    members = list(ClubSquadMembership.objects.select_for_update(of=("self",)).filter(club=club, player_id__in=ids)
                   .select_related("source_contract", "source_loan").order_by("player_id"))
    if len(members) != len(ids):
        raise FriendlyError("A selected player no longer belongs to the club.")
    today = timezone.localdate()
    for member in members:
        source = member.source_contract or member.source_loan
        start = source.start_date if member.source_contract_id else source.starts_on
        end = source.end_date if member.source_contract_id else source.ends_on
        if source.status != "ACTIVE" or not start <= today <= end:
            raise FriendlyError("A player's contract or loan is no longer active.")
    players = {str(p.pk): p for p in Player.objects.select_for_update().filter(pk__in=ids).order_by("pk").prefetch_related("position_familiarities")}
    if sum(p.position == "GK" for p in players.values()) < 2:
        raise FriendlyError("Selected squad requires at least two goalkeepers.")
    _validate_required_position_compatibility(starter_rows=rows, players_by_id=players)
    if any(not InjuryResolver.for_player(player=p).match_eligible for p in players.values()):
        raise FriendlyError("An unavailable injured player is selected.")
    def player_state(player_id, slot, role, tactical_role="AUTO"):
        return _player_state(SimpleNamespace(player=players[str(player_id)], slot=slot, role=role,
            tactical_role=tactical_role, is_captain=str(player_id) == str(data["captain_id"])), staff_effect=staff_effect)
    slots = FORMATION_SLOTS[data["formation"]]
    rows.sort(key=lambda r: slots.index(r["slot"]))
    return TeamState(club_id=str(club.pk), formation=data["formation"],
        starters=tuple(player_state(r["player_id"], r["slot"], "STARTER", r.get("tactical_role", "AUTO")) for r in rows),
        substitutes=tuple(player_state(i, "", "SUBSTITUTE") for i in data["substitutes"]))


@transaction.atomic
def prepare(game_id):
    from .engine.state import MatchState, MatchRules
    from .engine.registry import CURRENT_ENGINE_KEY, CURRENT_ENGINE_VERSION
    game = FriendlyGame.objects.select_for_update().get(pk=game_id)
    if game.status == "RUNNING":
        return game
    if game.status != "APPROVED" or game.scheduled_at > timezone.now():
        raise FriendlyError("Friendly is not approved or not due.")
    clubs = _participants(game)
    _independent(clubs)
    _supervision_valid(game, clubs)
    _no_conflict(game)
    # Match kickoff and transfers lock Player before Roster. Lock the complete
    # two-club player set in UUID order before _team takes any membership lock.
    # This also stabilizes automatic XI selection while the snapshot is built.
    from players.models import Player
    list(Player.objects.select_for_update(of=("self",)).filter(
        squad_membership__club_id__in=[c.pk for c in clubs]
    ).order_by("pk").values_list("pk", flat=True))
    from clubs.operations import stadium_for
    from staff.match_effects import current_effect
    venues = {str(c.pk): stadium_for(c) for c in clubs}
    if any(v is None for v in venues.values()):
        raise FriendlyError("Both clubs require an active owned or leased stadium before kickoff.")
    effects = {str(c.pk): current_effect(c.pk) for c in clubs}
    by_id = {c.pk: c for c in clubs}
    from .default_lineups import DefaultLineupService
    from .engine.state import TeamTacticalContext
    from .tactical_catalog import validate_plan
    plans = {c.pk: TeamTacticalContext.from_payload(validate_plan(DefaultLineupService.get_for_club(club=c).get("tactical_plan") or {})) for c in clubs}
    state = MatchState(match_id=str(game.pk), fixture_id=str(game.pk), competition_id=f"friendly:{game.pk}",
        season_id="FRIENDLY", home=_team(by_id[game.home_club_id], staff_effect=effects[str(game.home_club_id)]), away=_team(by_id[game.away_club_id], staff_effect=effects[str(game.away_club_id)]),
        home_tactics=plans[game.home_club_id], away_tactics=plans[game.away_club_id],
        rules=MatchRules(requires_winner=False, allows_extra_time=False, allows_penalties=False))
    game.seed = secrets.randbelow(2**63 - 1) + 1
    game.engine_key, game.engine_version = CURRENT_ENGINE_KEY, CURRENT_ENGINE_VERSION
    game.state_payload = state.to_payload()
    game.state_hash = payload_sha256({"seed": game.seed, "engine": [game.engine_key, game.engine_version], "state": game.state_payload})
    game.status, game.started_at = "RUNNING", timezone.now()
    game.save()
    _audit(game, None, "SNAPSHOT", state_hash=game.state_hash, staff_effects=effects, stadiums={key:str(value.pk) for key,value in venues.items()})
    return game


def simulate(game_id):
    from .engine.state import MatchState
    from .engine.registry import engine_class
    game = prepare(game_id)
    expected = payload_sha256({"seed": game.seed, "engine": [game.engine_key, game.engine_version], "state": game.state_payload})
    if expected != game.state_hash:
        raise FriendlyError("Friendly snapshot integrity mismatch.")
    outcome = engine_class(game.engine_key, game.engine_version)().simulate(MatchState.from_payload(game.state_payload), seed=game.seed)
    payload = {"result": outcome.result.to_payload(), "resolution": outcome.resolution.to_payload(), "report": outcome.report.to_payload()}
    # JSONB-safe normalization is also used by official causal engine persistence.
    from .report_integrity import normalize_report_payload_for_jsonb
    payload = normalize_report_payload_for_jsonb(payload)
    with transaction.atomic():
        current = FriendlyGame.objects.select_for_update().get(pk=game_id)
        if current.status != "RUNNING" or current.state_hash != game.state_hash:
            if current.status in {"REVIEW", "SETTLED"}:
                return current
            raise FriendlyError("Friendly state changed during execution.")
        current.result_payload = payload
        current.result_hash = payload_sha256({"state_hash": current.state_hash, "outcome": payload})
        current.home_score, current.away_score = outcome.result.home_score, outcome.result.away_score
        current.status, current.completed_at = "REVIEW", timezone.now()
        current.save()
        _audit(current, None, "RESULT", result_hash=current.result_hash)
        return current


@transaction.atomic
def decide(*, user, game_id, version, action, note, result_hash=""):
    game = FriendlyGame.objects.select_for_update().get(pk=game_id)
    clubs = _participants(game)
    _governor(user, game, clubs)
    if game.version != version or game.status in {"SETTLED", "VOID", "DECLINED"} or not str(note).strip():
        raise FriendlyError("Current unresolved friendly and a decision reason are required.")
    if action == "settle":
        if game.status != "REVIEW" or game.result_hash != result_hash:
            raise FriendlyError("Review the exact completed result before settlement.")
        state_hash = payload_sha256({"seed": game.seed, "engine": [game.engine_key, game.engine_version], "state": game.state_payload})
        if state_hash != game.state_hash:
            raise FriendlyError("Sealed engine input was altered; settlement blocked.")
        expected = payload_sha256({"state_hash": game.state_hash, "outcome": game.result_payload})
        if expected != game.result_hash or (game.home_score, game.away_score) != (
            game.result_payload["result"]["home_score"], game.result_payload["result"]["away_score"]):
            raise FriendlyError("Result evidence mismatch; settlement blocked.")
    elif action != "void":
        raise FriendlyError("Unknown federation decision.")
    if game.stake > 0 and game.home_reservation_id:
        escrow = Wallet.objects.get(wallet_type=WalletType.FRIENDLY_ESCROW)
        wallets = {c.pk: WalletService.get_club_wallet(club=c) for c in clubs}
        WalletService.lock_wallets_canonically(wallets=[escrow, *wallets.values()])
        for side in ("home", "away"):
            receipt = getattr(game, f"{side}_reservation")
            if (receipt.amount != game.stake or receipt.transaction_type != Tx.FRIENDLY_RESERVE or
                receipt.reference_type != "friendly_reserve" or receipt.reference_id != str(game.pk) or
                receipt.source_wallet_id != wallets[getattr(game, f"{side}_club_id")].pk or
                receipt.destination_wallet_id != escrow.pk):
                raise FriendlyError("Escrow reservation evidence mismatch; settlement blocked.")
        # Return principal to both clubs and transfer the loser's contribution
        # to the winner atomically. Only the net win is income; principal is
        # not fake turnover for FFP. Wallet locks cover all three movements.
        receipts={game.home_club_id:game.home_reservation,game.away_club_id:game.away_reservation}
        payouts = [(wallets[c.pk], game.stake, str(c.pk), Tx.FRIENDLY_REFUND) for c in clubs]
        for wallet, amount, suffix, tx_type in payouts:
            EconomyTransferService.transfer(source_wallet=escrow, destination_wallet=wallet, amount=amount,
                funding_entry=receipts[wallet.club_id],transaction_type=tx_type, reference_type="friendly_settlement", reference_id=str(game.pk),
                idempotency_key=f"friendly:{game.pk}:settle:{suffix}", description="تسویه بازی دوستانه با رأی فدراسیون.")
        if action == "settle" and game.home_score != game.away_score:
            winner = game.home_club_id if game.home_score > game.away_score else game.away_club_id
            loser = game.away_club_id if winner == game.home_club_id else game.home_club_id
            EconomyTransferService.transfer(source_wallet=wallets[loser], destination_wallet=wallets[winner], amount=game.stake,
                backed_amount=receipts[loser].backed_amount,transaction_type=Tx.FRIENDLY_PRIZE, reference_type="friendly_settlement", reference_id=str(game.pk),
                idempotency_key=f"friendly:{game.pk}:settle:net-prize", description="سهم خالص حریف به برنده؛ با تأیید فدراسیون.")
    game.status, game.decided_by, game.decision_note = ("SETTLED" if action == "settle" else "VOID"), user, note
    game.save()
    _audit(game, user, action.upper(), note=note, result_hash=game.result_hash)
    return game


def process_due(limit=10):
    ids = list(FriendlyGame.objects.filter(status__in=["APPROVED", "RUNNING"], scheduled_at__lte=timezone.now())
               .order_by("updated_at", "pk").values_list("pk", flat=True)[:limit])
    result = {"completed": 0, "blocked": 0}
    for game_id in ids:
        try:
            simulate(game_id)
            result["completed"] += 1
        except Exception as exc:
            result["blocked"] += 1
            # Funds stay in escrow; retries retain the same immutable snapshot.
            with transaction.atomic():
                game = FriendlyGame.objects.select_for_update().get(pk=game_id)
                if game.status in {"APPROVED", "RUNNING"}:
                    reason = str(exc) if isinstance(exc, FriendlyError) else type(exc).__name__
                    last = game.audit.order_by("-created_at", "-id").first()
                    if not last or last.action != "BLOCKED" or last.evidence.get("reason") != reason:
                        _audit(game, None, "BLOCKED", reason=reason)
                    game.save(update_fields=["updated_at"])
    return result
