"""Small, versioned formation-learning effect; existing replay engines stay frozen."""
from dataclasses import replace

from matches.engine.v314.engine import FTGMatchEngineV314


def cohesion(team, players):
    # A changed shape must not inherit learning from the starting system.
    trained_slots = {p.lineup_slot for p in team.starters}
    if not players or not {p.lineup_slot for p in players} <= trained_slots:
        return 0.0
    learned = dict(team.formation_training)
    return sum(learned.get(p.player_id, 0.0) for p in players) / len(players)


class FTGMatchEngineV315(FTGMatchEngineV314):
    version = "3.15.0"

    def simulate(self, state, *, seed, commands=()):
        outcome = super().simulate(state, seed=seed, commands=commands)
        return replace(outcome, report=replace(outcome.report, advanced_analytics={
            **outcome.report.advanced_analytics,
            "formation_training": {"policy": "1.0.0", "maximum_bonus": 0.03,
                "home": cohesion(state.home, state.home.starters),
                "away": cohesion(state.away, state.away.starters)},
        }))

    def _chance_probability(self, **kwargs):
        base = super()._chance_probability(**kwargs)
        state = kwargs["state"]
        home = kwargs["attacking_club"] == state.home.club_id
        own, other = (state.home, state.away) if home else (state.away, state.home)
        attack = cohesion(own, kwargs["attack_players"])
        defence = cohesion(other, kwargs["defend_players"])
        from matches.engine.v3.config import MIN_CHANCE_PROBABILITY, MAX_CHANCE_PROBABILITY
        return max(MIN_CHANCE_PROBABILITY, min(MAX_CHANCE_PROBABILITY,
            base * (1 + attack * 0.0003) / (1 + defence * 0.0003)))
