"""Pure diagnostic simulations: no club, player, wallet or match rows are written."""

import json
from pathlib import Path

from django.core.management.base import BaseCommand, CommandError

from matches.constants import FORMATION_SLOTS, AttackingStrategy, DefensiveStrategy
from matches.engine.registry import CurrentMatchEngine
from matches.engine.roles import SLOT_TARGET_POSITION
from matches.engine.shape_matchup import evaluate_pair, interaction, profile
from matches.engine.state import MatchState, PlayerState, TeamState, TeamTacticalContext
from players.models import PLAYER_RATING_FIELDS


def diagnostic_team(formation, club_id, quality=70):
    ratings = tuple(
        sorted(
            {**dict.fromkeys(PLAYER_RATING_FIELDS, quality), "overall": quality}.items()
        )
    )
    return TeamState(
        club_id=club_id,
        formation=formation,
        starters=tuple(
            PlayerState(
                player_id=f"{club_id}-{i}",
                natural_position=SLOT_TARGET_POSITION[slot],
                lineup_slot=slot,
                role="STARTER",
                is_captain=i == 1,
                ratings=ratings,
            )
            for i, slot in enumerate(FORMATION_SLOTS[formation])
        ),
        substitutes=(),
    )


class Command(BaseCommand):
    help = "Evaluate every prepared shape and simulate the diamond/double-pivot example with neutral players."

    def add_arguments(self, parser):
        parser.add_argument("--seeds", type=int, default=4)
        parser.add_argument("--output", default="docs/TACTICAL_MATCHUP_EVALUATION.json")

    def handle(self, *args, **options):
        seeds = options["seeds"]
        if not 1 <= seeds <= 100:
            raise CommandError("Use 1..100 seeds per scenario and venue.")
        teams = {
            code: diagnostic_team(code, code)
            for code in FORMATION_SLOTS
            if code != "CUSTOM"
        }
        baseline = {code: profile(team.starters) for code, team in teams.items()}
        matrix = [
            {
                "own": code,
                "opponent": other,
                "factor": interaction(own, opponent)["chance_factor"],
            }
            for code, own in baseline.items()
            for other, opponent in baseline.items()
        ]
        diamond = teams["4-4-2-D"].starters
        double = teams["4-3-3-2DM"].starters
        variations = [
            {
                "attack": attack,
                "defence": defence,
                "evaluation": evaluate_pair(
                    diamond, double, attack, defence, "WIDE_PLAY", "MID_BLOCK"
                ),
            }
            for attack in AttackingStrategy.values
            for defence in DefensiveStrategy.values
        ]
        scenarios = [
            ("CONTROL_V_WIDE", "POSSESSION", "MID_BLOCK", "WIDE_PLAY", "MID_BLOCK"),
            ("DIRECT_V_PRESS", "DIRECT", "LOW_BLOCK", "POSSESSION", "HIGH_PRESS"),
            (
                "PRESS_V_COUNTER",
                "HIGH_TEMPO",
                "HIGH_PRESS",
                "COUNTER_ATTACK",
                "LOW_BLOCK",
            ),
            (
                "CONTROL_V_COMPACT",
                "POSSESSION",
                "ZONAL_COMPACT",
                "BALANCED",
                "ZONAL_COMPACT",
            ),
        ]
        observations = []
        for label, attack, defence, other_attack, other_defence in scenarios:
            matches = []
            for swapped in (False, True):
                first = diagnostic_team("4-4-2-D", "diamond")
                second = diagnostic_team("4-3-3-2DM", "double_pivot")
                first_tactics = TeamTacticalContext(
                    attacking_strategy=attack,
                    defensive_strategy=defence,
                    adaptation_mode="STATIC",
                )
                second_tactics = TeamTacticalContext(
                    attacking_strategy=other_attack,
                    defensive_strategy=other_defence,
                    adaptation_mode="STATIC",
                )
                state = MatchState(
                    match_id="diagnostic",
                    fixture_id="diagnostic",
                    competition_id="diagnostic",
                    season_id="diagnostic",
                    home=second if swapped else first,
                    away=first if swapped else second,
                    home_tactics=second_tactics if swapped else first_tactics,
                    away_tactics=first_tactics if swapped else second_tactics,
                )
                for index in range(seeds):
                    seed = 314000 + index
                    outcome = CurrentMatchEngine().simulate(state, seed=seed)
                    result = outcome.result
                    stats = {
                        row["club_id"]: row
                        for row in outcome.report.advanced_analytics["team_statistics"]
                    }
                    matches.append(
                        {
                            "seed": seed,
                            "diamond_home": not swapped,
                            "diamond_goals": result.away_score
                            if swapped
                            else result.home_score,
                            "double_pivot_goals": result.home_score
                            if swapped
                            else result.away_score,
                            "diamond_xg": stats["diamond"]["xg"],
                            "double_pivot_xg": stats["double_pivot"]["xg"],
                        }
                    )
            count = len(matches)
            row = {
                "scenario": label,
                "diamond_tactics": [attack, defence],
                "double_pivot_tactics": [other_attack, other_defence],
                "matches": count,
                "diamond_wins": sum(
                    r["diamond_goals"] > r["double_pivot_goals"] for r in matches
                ),
                "draws": sum(
                    r["diamond_goals"] == r["double_pivot_goals"] for r in matches
                ),
                "double_pivot_wins": sum(
                    r["diamond_goals"] < r["double_pivot_goals"] for r in matches
                ),
                "mean_diamond_xg": round(
                    sum(r["diamond_xg"] for r in matches) / count, 3
                ),
                "mean_double_pivot_xg": round(
                    sum(r["double_pivot_xg"] for r in matches) / count, 3
                ),
                "observations": matches,
            }
            observations.append(row)
            self.stdout.write(
                json.dumps({k: v for k, v in row.items() if k != "observations"})
            )
            self.stdout.flush()
        report = {
            "engine": CurrentMatchEngine.version,
            "prepared_formations": len(teams),
            "baseline_pairings": len(matrix),
            "seeds_per_scenario_and_venue": seeds,
            "simulated_matches": sum(r["matches"] for r in observations),
            "quality": 70,
            "equal_attributes": True,
            "adaptation": "STATIC",
            "substitutes": 0,
            "limits": [
                "Small diagnostic sample, not calibrated real-world win probabilities.",
                "Equal attributes and no bench isolate shape/tactic effects.",
                "Home and away venues are paired; normal stochastic cards/injuries remain enabled.",
            ],
            "baseline_matrix": matrix,
            "diamond_tactical_variations": variations,
            "scenarios": observations,
        }
        path = Path(options["output"])
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(
            json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
        )
        self.stdout.write(
            self.style.SUCCESS(
                f"Saved {path}: {report['simulated_matches']} diagnostic matches; source data unchanged."
            )
        )
