"""Versioned spatial formation/tactic interaction; old replay engines stay frozen."""

from dataclasses import replace

from matches.engine.shape_matchup import evaluate_pair
from matches.engine.v3131.engine import FTGMatchEngineV3131

from .evaluator import evaluate_team


class FTGMatchEngineV314(FTGMatchEngineV3131):
    version = "3.14.0"
    _evaluate_team = staticmethod(evaluate_team)

    def simulate(self, state, *, seed, commands=()):
        self._matchup_samples = {}
        outcome = super().simulate(state, seed=seed, commands=commands)
        evidence = evaluate_pair(
            state.home.starters,
            state.away.starters,
            state.home_tactics.attacking_strategy,
            state.home_tactics.defensive_strategy,
            state.away_tactics.attacking_strategy,
            state.away_tactics.defensive_strategy,
        )
        report = replace(
            outcome.report,
            advanced_analytics={
                **outcome.report.advanced_analytics,
                "formation_matchup": {
                    "kickoff": evidence,
                    "samples": list(self._matchup_samples.values()),
                },
            },
        )
        return replace(outcome, report=report)

    def _chance_probability(self, **kwargs):
        base = super()._chance_probability(**kwargs)
        state = kwargs["state"]
        home_attacking = kwargs["attacking_club"] == state.home.club_id
        own = state.home_tactics if home_attacking else state.away_tactics
        other = state.away_tactics if home_attacking else state.home_tactics
        matchup = evaluate_pair(
            kwargs["attack_players"],
            kwargs["defend_players"],
            kwargs["attack_strategy"],
            own.defensive_strategy,
            other.attacking_strategy,
            kwargs["defending_strategy"],
            kwargs["minute"],
        )
        key = (
            kwargs["attacking_club"],
            kwargs["minute"] // 15,
            kwargs["attack_strategy"],
            kwargs["defending_strategy"],
            tuple(p.player_id for p in kwargs["attack_players"]),
            tuple(p.player_id for p in kwargs["defend_players"]),
        )
        self._matchup_samples.setdefault(
            key,
            {
                "minute": kwargs["minute"],
                "attacking_club": kwargs["attacking_club"],
                "attacking_strategy": kwargs["attack_strategy"],
                "defending_strategy": kwargs["defending_strategy"],
                "attack_player_count": len(kwargs["attack_players"]),
                "defend_player_count": len(kwargs["defend_players"]),
                **matchup["home"],
            },
        )
        from matches.engine.v3.config import (
            MAX_CHANCE_PROBABILITY,
            MIN_CHANCE_PROBABILITY,
        )

        return max(
            MIN_CHANCE_PROBABILITY,
            min(MAX_CHANCE_PROBABILITY, base * matchup["home"]["chance_factor"]),
        )

    def _possession_share(
        self, *, state, evaluation, current, minute, home_reds, away_reds
    ):
        base = super()._possession_share(
            state=state,
            evaluation=evaluation,
            current=current,
            minute=minute,
            home_reds=home_reds,
            away_reds=away_reds,
        )
        home, away = current[state.home.club_id], current[state.away.club_id]
        matchup = evaluate_pair(
            state.home.starters, state.away.starters, *home, *away, minute
        )
        from matches.engine.v3.config import MAX_POSSESSION_SHARE, MIN_POSSESSION_SHARE

        return max(
            MIN_POSSESSION_SHARE,
            min(
                MAX_POSSESSION_SHARE,
                base
                + (
                    matchup["home"]["possession_delta"]
                    - matchup["away"]["possession_delta"]
                )
                / 2,
            ),
        )
