use crate::operational::bot_sandbox::{
    ArenaMatchMode, BotMatchExecution, BotMatchOutcome, BotMatchReplay, BotSandbox,
    TeamBattleOutcome,
};
use base64::Engine as _;
use dashmap::DashMap;
use futures_util::stream::{self, StreamExt};
use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::convert::Infallible;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use subtle::ConstantTimeEq;
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
use tracing::{info, warn};
use uuid::Uuid;
use warp::{Filter, Reply};

const DEFAULT_ARENA_LEADERBOARD_LIMIT: usize = 25;
const MAX_ARENA_LEADERBOARD_LIMIT: usize = 100;
const DEFAULT_ARENA_PENDING_LIMIT: usize = 20;
const DEFAULT_ARENA_RECENT_REPLAY_LIMIT: usize = 20;
const DEFAULT_BASE_ELO: f64 = 1000.0;
const DEFAULT_ARENA_WASM_DIR: &str = "data/arena_bots";
const DEFAULT_ARENA_WASM_MAX_BYTES: usize = 2 * 1024 * 1024;
const DEFAULT_ARENA_REPLAY_HISTORY_CAP: usize = 256;
const DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP: usize = 4_096;
const DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP: usize = 256;
const DEFAULT_ARENA_REPLAY_EVENTS_LIMIT: usize = 256;
const DEFAULT_ARENA_REPLAY_STREAM_BACKLOG: usize = 64;
const DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP: usize = 1_024;
const MAX_ARENA_PENDING_MATCHES: usize = 10_000;
const MAX_MODEL_ID_LEN: usize = 128;
const MAX_ARENA_REPLAY_HISTORY_CAP: usize = 4096;
const MAX_ARENA_REPLAY_EVENT_HISTORY_CAP: usize = 32_768;
const MAX_ARENA_REPLAY_MATCH_HISTORY_CAP: usize = 4_096;
const MAX_ARENA_REPLAY_EVENTS_LIMIT: usize = 2_048;
const MAX_ARENA_REPLAY_WARNINGS: usize = 24;
const MAX_ARENA_STREAM_BACKLOG: usize = 2_048;
const DEFAULT_ARENA_IN_FLIGHT_TTL_SECS: u64 = 30 * 60;
const MAX_ARENA_IN_FLIGHT_TTL_SECS: u64 = 24 * 60 * 60;

fn arena_in_flight_ttl_secs() -> u64 {
    static TTL_SECS: OnceLock<u64> = OnceLock::new();
    *TTL_SECS.get_or_init(|| {
        std::env::var("MGS_ARENA_IN_FLIGHT_TTL_SECS")
            .ok()
            .and_then(|raw| raw.trim().parse::<u64>().ok())
            .unwrap_or(DEFAULT_ARENA_IN_FLIGHT_TTL_SECS)
            .clamp(60, MAX_ARENA_IN_FLIGHT_TTL_SECS)
    })
}

#[derive(Clone)]
pub struct ArenaService {
    inner: Arc<ArenaInner>,
}

struct ArenaInner {
    store_path: PathBuf,
    bot_sandbox: BotSandbox,
    wasm_dir: PathBuf,
    wasm_max_bytes: usize,
    persistent_store: RwLock<PersistentArenaStore>,
    pending_matches: Mutex<VecDeque<QueuedMatch>>,
    in_flight_matches: DashMap<String, QueuedMatch>,
    total_matches_reported: AtomicU64,
    worker_runs: AtomicU64,
    worker_executed: AtomicU64,
    worker_idle: AtomicU64,
    worker_failures: AtomicU64,
    worker_last_success_at: AtomicU64,
    worker_last_failure_at: AtomicU64,
    worker_last_error: RwLock<Option<String>>,
    worker_total_duration_ms: AtomicU64,
    worker_total_ticks: AtomicU64,
    worker_warning_matches: AtomicU64,
    worker_runtime_fallback_matches: AtomicU64,
    worker_trap_warnings: AtomicU64,
    worker_timeout_warnings: AtomicU64,
    worker_draw_matches: AtomicU64,
    worker_max_duration_ms: AtomicU64,
    worker_min_duration_ms: AtomicU64,
    worker_model_win_distribution: RwLock<HashMap<String, u64>>,
    replay_sequence: AtomicU64,
    replay_history_capacity: usize,
    recent_replays: Mutex<VecDeque<ArenaReplayView>>,
    replay_event_sequence: AtomicU64,
    replay_event_history_capacity: usize,
    replay_match_history_capacity: usize,
    replay_events: Mutex<VecDeque<ArenaReplayEvent>>,
    replay_match_order: Mutex<VecDeque<String>>,
    replay_matches: RwLock<HashMap<String, ArenaMatchReplayRecord>>,
    replay_event_tx: broadcast::Sender<ArenaReplayEvent>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct PersistentArenaStore {
    models: HashMap<String, ArenaModelRecord>,
    completed_matches: Vec<CompletedMatchRecord>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ArenaModelRecord {
    model_id: String,
    model_name: String,
    provider: String,
    version: String,
    active: bool,
    created_at: u64,
    updated_at: u64,
    last_seen_at: u64,
    elo_rating: f64,
    matches_played: u64,
    wins: u64,
    losses: u64,
    draws: u64,
    cumulative_score: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct CompletedMatchRecord {
    match_id: String,
    model_a_id: String,
    model_b_id: String,
    winner_model_id: Option<String>,
    draw: bool,
    model_a_score: i32,
    model_b_score: i32,
    duration_ms: Option<u64>,
    completed_at: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct QueuedMatch {
    match_id: String,
    model_a_id: String,
    model_b_id: String,
    mode: String,
    queued_at: u64,
    metadata: HashMap<String, String>,
}

#[derive(Debug, Clone)]
struct ArenaMatchReplayRecord {
    match_id: String,
    mode: String,
    model_a_id: String,
    model_b_id: String,
    seed: u64,
    max_ticks: u32,
    ticks_executed: u32,
    duration_ms: u64,
    winner_model_id: Option<String>,
    draw: bool,
    warnings: Vec<String>,
    truncated: bool,
    total_frames: usize,
    completed_at: u64,
    events: Vec<ArenaReplayEvent>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaModelView {
    pub model_id: String,
    pub model_name: String,
    pub provider: String,
    pub version: String,
    pub active: bool,
    pub elo_rating: f64,
    pub matches_played: u64,
    pub wins: u64,
    pub losses: u64,
    pub draws: u64,
    pub cumulative_score: i64,
    pub win_rate: f64,
    pub created_at: u64,
    pub updated_at: u64,
    pub last_seen_at: u64,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaLeaderboardResponse {
    pub generated_at: u64,
    pub total_models: usize,
    pub total_completed_matches: usize,
    pub models: Vec<ArenaModelView>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaOverviewResponse {
    pub generated_at: u64,
    pub active_models: usize,
    pub pending_matches: usize,
    pub in_flight_matches: usize,
    pub total_completed_matches: usize,
    pub total_matches_reported_runtime: u64,
}

#[derive(Debug, Clone, Serialize)]
pub struct QueueMatchResponse {
    pub queued_count: usize,
    pub pending_total: usize,
    pub queued_matches: Vec<QueuedMatchView>,
}

#[derive(Debug, Clone, Serialize)]
pub struct QueuedMatchView {
    pub match_id: String,
    pub model_a_id: String,
    pub model_b_id: String,
    pub mode: String,
    pub queued_at: u64,
}

#[derive(Debug, Clone, Serialize)]
pub struct ClaimMatchResponse {
    pub claimed: Option<QueuedMatchView>,
    pub pending_total: usize,
    pub in_flight_total: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct ReportMatchResponse {
    pub match_id: String,
    pub completed_at: u64,
    pub model_a: ArenaModelView,
    pub model_b: ArenaModelView,
}

#[derive(Debug, Clone, Serialize)]
pub struct ExecuteNextMatchResponse {
    pub pending_before: usize,
    pub pending_after: usize,
    pub report: ReportMatchResponse,
    pub sandbox: BotMatchOutcome,
}

#[derive(Debug, Clone, Serialize)]
pub struct SimulateTeamBattleResponse {
    pub generated_at: u64,
    pub simulation: TeamBattleOutcome,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaReplayView {
    pub replay_id: String,
    pub match_id: String,
    pub executed_at: u64,
    pub mode: String,
    pub model_a_id: String,
    pub model_b_id: String,
    pub winner_model_id: Option<String>,
    pub draw: bool,
    pub model_a_score: i32,
    pub model_b_score: i32,
    pub objective_label: String,
    pub objective_a: i32,
    pub objective_b: i32,
    pub model_a_runtime: String,
    pub model_b_runtime: String,
    pub ticks_executed: u32,
    pub duration_ms: u64,
    pub warnings: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaReplayListResponse {
    pub generated_at: u64,
    pub total_replays: usize,
    pub replays: Vec<ArenaReplayView>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaReplayEvent {
    pub sequence: u64,
    pub emitted_at: u64,
    pub match_id: String,
    pub mode: String,
    pub event_type: String,
    pub tick: Option<u32>,
    pub action_model_a: Option<String>,
    pub action_model_b: Option<String>,
    pub health_model_a: Option<i32>,
    pub health_model_b: Option<i32>,
    pub score_model_a: Option<i32>,
    pub score_model_b: Option<i32>,
    pub objective_a: Option<i32>,
    pub objective_b: Option<i32>,
    pub winner_model_id: Option<String>,
    pub draw: Option<bool>,
    pub duration_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaReplayEventFeedResponse {
    pub generated_at: u64,
    pub total_events: usize,
    pub returned_events: usize,
    pub newest_sequence: Option<u64>,
    pub events: Vec<ArenaReplayEvent>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaMatchReplayResponse {
    pub generated_at: u64,
    pub match_id: String,
    pub mode: String,
    pub model_a_id: String,
    pub model_b_id: String,
    pub seed: u64,
    pub max_ticks: u32,
    pub ticks_executed: u32,
    pub duration_ms: u64,
    pub winner_model_id: Option<String>,
    pub draw: bool,
    pub truncated: bool,
    pub total_frames: usize,
    pub total_events: usize,
    pub returned_events: usize,
    pub completed_at: u64,
    pub warnings: Vec<String>,
    pub events: Vec<ArenaReplayEvent>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ArenaWorkerStatsResponse {
    pub generated_at: u64,
    pub pending_matches: usize,
    pub in_flight_matches: usize,
    pub runs: u64,
    pub executed: u64,
    pub idle: u64,
    pub failures: u64,
    pub last_success_at: Option<u64>,
    pub last_failure_at: Option<u64>,
    pub last_error: Option<String>,
    pub total_match_duration_ms: u64,
    pub avg_match_duration_ms: f64,
    pub max_match_duration_ms: u64,
    pub min_match_duration_ms: Option<u64>,
    pub total_ticks_executed: u64,
    pub avg_ticks_executed: f64,
    pub warning_matches: u64,
    pub runtime_fallback_matches: u64,
    pub trap_warnings: u64,
    pub timeout_warnings: u64,
    pub draw_matches: u64,
    pub model_win_distribution: HashMap<String, u64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct UploadModelWasmResponse {
    pub model_id: String,
    pub wasm_path: String,
    pub bytes_written: usize,
    pub overwritten: bool,
}

#[derive(Debug, Clone, Deserialize)]
struct RegisterModelBody {
    model_id: Option<String>,
    model_name: String,
    provider: Option<String>,
    version: Option<String>,
    active: Option<bool>,
    initial_elo: Option<f64>,
}

#[derive(Debug, Clone, Deserialize)]
struct ModelHeartbeatBody {
    model_id: String,
}

#[derive(Debug, Clone, Deserialize)]
struct UploadModelWasmBody {
    model_id: String,
    wasm_base64: String,
    overwrite: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
struct QueueMatchBody {
    model_a_id: String,
    model_b_id: String,
    mode: Option<String>,
    metadata: Option<HashMap<String, String>>,
}

#[derive(Debug, Clone, Deserialize)]
struct QueueRoundRobinBody {
    mode: Option<String>,
    include_inactive: Option<bool>,
    max_pairs: Option<usize>,
}

#[derive(Debug, Clone, Deserialize)]
struct ReportMatchBody {
    match_id: String,
    model_a_id: Option<String>,
    model_b_id: Option<String>,
    winner_model_id: Option<String>,
    draw: Option<bool>,
    model_a_score: Option<i32>,
    model_b_score: Option<i32>,
    duration_ms: Option<u64>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct LeaderboardQuery {
    limit: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct PendingQuery {
    limit: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct ReplayQuery {
    limit: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct ReplayEventsQuery {
    limit: Option<usize>,
    after_sequence: Option<u64>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct ReplayStreamQuery {
    after_sequence: Option<u64>,
    backlog: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct ExecuteNextBody {
    max_ticks: Option<u32>,
    seed: Option<u64>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct SimulateTeamBattleBody {
    model_a_id: String,
    model_b_id: String,
    mode: Option<String>,
    team_size: Option<u32>,
    rounds: Option<u32>,
    max_ticks: Option<u32>,
    seed: Option<u64>,
}

#[derive(Debug, Clone, Serialize)]
struct ApiErrorBody {
    code: &'static str,
    message: String,
}

#[derive(Debug, Clone, Serialize)]
struct ApiResponse<T>
where
    T: Serialize,
{
    ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<T>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<ApiErrorBody>,
}

#[derive(Debug)]
enum ArenaError {
    InvalidInput(&'static str, String),
    NotFound(&'static str, String),
    Conflict(&'static str, String),
    Internal(String),
}

impl ArenaError {
    fn code(&self) -> &'static str {
        match self {
            ArenaError::InvalidInput(code, _) => code,
            ArenaError::NotFound(code, _) => code,
            ArenaError::Conflict(code, _) => code,
            ArenaError::Internal(_) => "internal_error",
        }
    }

    fn message(&self) -> String {
        match self {
            ArenaError::InvalidInput(_, msg)
            | ArenaError::NotFound(_, msg)
            | ArenaError::Conflict(_, msg)
            | ArenaError::Internal(msg) => msg.clone(),
        }
    }
}

impl ArenaService {
    fn prune_stale_in_flight_matches(&self) {
        let ttl_secs = arena_in_flight_ttl_secs();
        let now = unix_now();
        let mut removed = 0usize;
        self.inner.in_flight_matches.retain(|_match_id, queued| {
            let keep = now.saturating_sub(queued.queued_at) <= ttl_secs;
            if !keep {
                removed += 1;
            }
            keep
        });
        if removed > 0 {
            warn!(
                "Pruned {} stale arena in-flight matches older than {} seconds",
                removed, ttl_secs
            );
        }
    }

    pub fn new_from_env() -> Self {
        let store_path = std::env::var("MGS_ARENA_STORE_PATH")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("data/arena_store.json"));
        let wasm_dir = std::env::var("MGS_ARENA_WASM_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from(DEFAULT_ARENA_WASM_DIR));
        let wasm_max_bytes = std::env::var("MGS_ARENA_WASM_MAX_BYTES")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .filter(|value| *value > 1024)
            .unwrap_or(DEFAULT_ARENA_WASM_MAX_BYTES);
        let replay_history_capacity = std::env::var("MGS_ARENA_REPLAY_HISTORY_CAP")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .unwrap_or(DEFAULT_ARENA_REPLAY_HISTORY_CAP)
            .clamp(16, MAX_ARENA_REPLAY_HISTORY_CAP);
        let replay_event_history_capacity = std::env::var("MGS_ARENA_REPLAY_EVENT_HISTORY_CAP")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .unwrap_or(DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP)
            .clamp(128, MAX_ARENA_REPLAY_EVENT_HISTORY_CAP);
        let replay_match_history_capacity = std::env::var("MGS_ARENA_REPLAY_MATCH_HISTORY_CAP")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .unwrap_or(DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP)
            .clamp(16, MAX_ARENA_REPLAY_MATCH_HISTORY_CAP);
        let replay_stream_channel_cap = std::env::var("MGS_ARENA_REPLAY_STREAM_CHANNEL_CAP")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .unwrap_or(DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP)
            .clamp(64, 65_536);
        let (replay_event_tx, _) = broadcast::channel(replay_stream_channel_cap);
        let persistent_store = load_persistent_store(&store_path);
        let completed_count = persistent_store.completed_matches.len() as u64;

        info!(
            "Arena service initialized. store_path='{}', wasm_dir='{}', models={}, completed_matches={}, replay_history_capacity={}, replay_event_history_capacity={}, replay_match_history_capacity={}, replay_stream_channel_cap={}",
            store_path.display(),
            wasm_dir.display(),
            persistent_store.models.len(),
            completed_count,
            replay_history_capacity,
            replay_event_history_capacity,
            replay_match_history_capacity,
            replay_stream_channel_cap
        );

        Self {
            inner: Arc::new(ArenaInner {
                store_path,
                bot_sandbox: BotSandbox::new_from_env(),
                wasm_dir,
                wasm_max_bytes,
                persistent_store: RwLock::new(persistent_store),
                pending_matches: Mutex::new(VecDeque::new()),
                in_flight_matches: DashMap::new(),
                total_matches_reported: AtomicU64::new(completed_count),
                worker_runs: AtomicU64::new(0),
                worker_executed: AtomicU64::new(0),
                worker_idle: AtomicU64::new(0),
                worker_failures: AtomicU64::new(0),
                worker_last_success_at: AtomicU64::new(0),
                worker_last_failure_at: AtomicU64::new(0),
                worker_last_error: RwLock::new(None),
                worker_total_duration_ms: AtomicU64::new(0),
                worker_total_ticks: AtomicU64::new(0),
                worker_warning_matches: AtomicU64::new(0),
                worker_runtime_fallback_matches: AtomicU64::new(0),
                worker_trap_warnings: AtomicU64::new(0),
                worker_timeout_warnings: AtomicU64::new(0),
                worker_draw_matches: AtomicU64::new(0),
                worker_max_duration_ms: AtomicU64::new(0),
                worker_min_duration_ms: AtomicU64::new(0),
                worker_model_win_distribution: RwLock::new(HashMap::new()),
                replay_sequence: AtomicU64::new(0),
                replay_history_capacity,
                recent_replays: Mutex::new(VecDeque::new()),
                replay_event_sequence: AtomicU64::new(0),
                replay_event_history_capacity,
                replay_match_history_capacity,
                replay_events: Mutex::new(VecDeque::new()),
                replay_match_order: Mutex::new(VecDeque::new()),
                replay_matches: RwLock::new(HashMap::new()),
                replay_event_tx,
            }),
        }
    }

    fn register_model(&self, body: RegisterModelBody) -> Result<ArenaModelView, ArenaError> {
        let model_name = body.model_name.trim();
        if model_name.is_empty() {
            return Err(ArenaError::InvalidInput(
                "invalid_model_name",
                "model_name cannot be empty".to_owned(),
            ));
        }

        let now = unix_now();
        let model_id = body
            .model_id
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(ToOwned::to_owned)
            .unwrap_or_else(|| format!("model_{}", Uuid::new_v4().simple()));

        let provider = body
            .provider
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or("custom")
            .to_owned();
        let version = body
            .version
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or("latest")
            .to_owned();
        let active = body.active.unwrap_or(true);
        let initial_elo = body
            .initial_elo
            .unwrap_or(DEFAULT_BASE_ELO)
            .clamp(100.0, 4000.0);

        {
            let mut store = self.inner.persistent_store.write();
            let entry = store
                .models
                .entry(model_id.clone())
                .or_insert_with(|| ArenaModelRecord {
                    model_id: model_id.clone(),
                    model_name: model_name.to_owned(),
                    provider: provider.clone(),
                    version: version.clone(),
                    active,
                    created_at: now,
                    updated_at: now,
                    last_seen_at: now,
                    elo_rating: initial_elo,
                    matches_played: 0,
                    wins: 0,
                    losses: 0,
                    draws: 0,
                    cumulative_score: 0,
                });

            entry.model_name = model_name.to_owned();
            entry.provider = provider;
            entry.version = version;
            entry.active = active;
            entry.updated_at = now;
            entry.last_seen_at = now;
            if entry.matches_played == 0 {
                entry.elo_rating = initial_elo;
            }
        }

        self.spawn_persist_store();

        self.get_model_view(&model_id).ok_or_else(|| {
            ArenaError::Internal("model registration verification failed".to_owned())
        })
    }

    fn heartbeat_model(&self, body: ModelHeartbeatBody) -> Result<ArenaModelView, ArenaError> {
        let now = unix_now();
        {
            let mut store = self.inner.persistent_store.write();
            let Some(model) = store.models.get_mut(body.model_id.trim()) else {
                return Err(ArenaError::NotFound(
                    "model_not_found",
                    format!("model '{}' does not exist", body.model_id.trim()),
                ));
            };
            model.last_seen_at = now;
            model.updated_at = now;
            model.active = true;
        }

        self.spawn_persist_store();

        self.get_model_view(body.model_id.trim())
            .ok_or_else(|| ArenaError::Internal("heartbeat verification failed".to_owned()))
    }

    fn upload_model_wasm(
        &self,
        body: UploadModelWasmBody,
    ) -> Result<UploadModelWasmResponse, ArenaError> {
        let model_id = body.model_id.trim();
        if model_id.is_empty() {
            return Err(ArenaError::InvalidInput(
                "invalid_model_id",
                "model_id is required".to_owned(),
            ));
        }
        let Some(safe_model_id) = sanitize_model_id(model_id) else {
            return Err(ArenaError::InvalidInput(
                "invalid_model_id",
                "model_id contains unsupported characters".to_owned(),
            ));
        };

        {
            let store = self.inner.persistent_store.read();
            if !store.models.contains_key(model_id) {
                return Err(ArenaError::NotFound(
                    "model_not_found",
                    format!("model '{}' does not exist", model_id),
                ));
            }
        }

        let wasm_bytes = base64::engine::general_purpose::STANDARD
            .decode(body.wasm_base64.trim())
            .map_err(|err| {
                ArenaError::InvalidInput("invalid_wasm_base64", format!("invalid base64: {}", err))
            })?;
        if wasm_bytes.is_empty() {
            return Err(ArenaError::InvalidInput(
                "empty_wasm",
                "decoded wasm payload is empty".to_owned(),
            ));
        }
        if wasm_bytes.len() > self.inner.wasm_max_bytes {
            return Err(ArenaError::InvalidInput(
                "wasm_too_large",
                format!(
                    "wasm payload exceeds max size ({} > {})",
                    wasm_bytes.len(),
                    self.inner.wasm_max_bytes
                ),
            ));
        }
        if wasm_bytes.len() < 4 || wasm_bytes[..4] != [0, 0x61, 0x73, 0x6d] {
            return Err(ArenaError::InvalidInput(
                "invalid_wasm_header",
                "payload is not a valid wasm module".to_owned(),
            ));
        }

        fs::create_dir_all(&self.inner.wasm_dir).map_err(|err| {
            ArenaError::Internal(format!(
                "failed to create wasm dir '{}': {}",
                self.inner.wasm_dir.display(),
                err
            ))
        })?;
        let wasm_path = self.inner.wasm_dir.join(format!("{}.wasm", safe_model_id));
        let overwrite = body.overwrite.unwrap_or(false);
        let existed = wasm_path.exists();
        if existed && !overwrite {
            return Err(ArenaError::Conflict(
                "wasm_exists",
                format!(
                    "wasm already exists for model '{}'; set overwrite=true to replace",
                    model_id
                ),
            ));
        }

        fs::write(&wasm_path, &wasm_bytes).map_err(|err| {
            ArenaError::Internal(format!(
                "failed to write wasm file '{}': {}",
                wasm_path.display(),
                err
            ))
        })?;

        {
            let now = unix_now();
            let mut store = self.inner.persistent_store.write();
            if let Some(model) = store.models.get_mut(model_id) {
                model.updated_at = now;
                model.last_seen_at = now;
            }
        }
        self.spawn_persist_store();

        Ok(UploadModelWasmResponse {
            model_id: model_id.to_owned(),
            wasm_path: wasm_path.display().to_string(),
            bytes_written: wasm_bytes.len(),
            overwritten: existed,
        })
    }

    fn queue_match(&self, body: QueueMatchBody) -> Result<QueueMatchResponse, ArenaError> {
        let model_a_id = body.model_a_id.trim();
        let model_b_id = body.model_b_id.trim();
        if model_a_id.is_empty() || model_b_id.is_empty() {
            return Err(ArenaError::InvalidInput(
                "invalid_model_id",
                "model_a_id and model_b_id are required".to_owned(),
            ));
        }
        if model_a_id == model_b_id {
            return Err(ArenaError::InvalidInput(
                "invalid_matchup",
                "model_a_id and model_b_id must be different".to_owned(),
            ));
        }

        let store = self.inner.persistent_store.read();
        if !store.models.contains_key(model_a_id) {
            return Err(ArenaError::NotFound(
                "model_not_found",
                format!("model '{}' does not exist", model_a_id),
            ));
        }
        if !store.models.contains_key(model_b_id) {
            return Err(ArenaError::NotFound(
                "model_not_found",
                format!("model '{}' does not exist", model_b_id),
            ));
        }
        drop(store);

        let mode = normalize_match_mode(body.mode.as_deref())?;
        let metadata = body.metadata.unwrap_or_default();
        let queued = QueuedMatch {
            match_id: format!("match_{}", Uuid::new_v4().simple()),
            model_a_id: model_a_id.to_owned(),
            model_b_id: model_b_id.to_owned(),
            mode,
            queued_at: unix_now(),
            metadata,
        };

        let mut pending = self.inner.pending_matches.lock();
        if pending.len() >= MAX_ARENA_PENDING_MATCHES {
            return Err(ArenaError::Conflict(
                "queue_full",
                format!(
                    "pending queue is full (max {} matches)",
                    MAX_ARENA_PENDING_MATCHES
                ),
            ));
        }
        pending.push_back(queued.clone());
        let pending_total = pending.len();
        drop(pending);

        Ok(QueueMatchResponse {
            queued_count: 1,
            pending_total,
            queued_matches: vec![to_queued_match_view(&queued)],
        })
    }

    fn queue_round_robin(
        &self,
        body: QueueRoundRobinBody,
    ) -> Result<QueueMatchResponse, ArenaError> {
        let include_inactive = body.include_inactive.unwrap_or(false);
        let mode = normalize_match_mode(body.mode.as_deref())?;
        let max_pairs = body.max_pairs.unwrap_or(512).max(1);
        let pending_before = self.inner.pending_matches.lock().len();
        if pending_before >= MAX_ARENA_PENDING_MATCHES {
            return Err(ArenaError::Conflict(
                "queue_full",
                format!(
                    "pending queue is full (max {} matches)",
                    MAX_ARENA_PENDING_MATCHES
                ),
            ));
        }
        let available_slots = MAX_ARENA_PENDING_MATCHES - pending_before;
        let capped_max_pairs = max_pairs.min(available_slots);

        let mut model_ids: Vec<String> = {
            let store = self.inner.persistent_store.read();
            store
                .models
                .values()
                .filter(|model| include_inactive || model.active)
                .map(|model| model.model_id.clone())
                .collect()
        };
        model_ids.sort_unstable();
        if model_ids.len() < 2 {
            return Err(ArenaError::InvalidInput(
                "not_enough_models",
                "need at least 2 models to queue round-robin matches".to_owned(),
            ));
        }

        let mut queued_matches = Vec::new();
        let now = unix_now();
        'outer: for left in 0..model_ids.len() {
            for right in (left + 1)..model_ids.len() {
                let queued = QueuedMatch {
                    match_id: format!("match_{}", Uuid::new_v4().simple()),
                    model_a_id: model_ids[left].clone(),
                    model_b_id: model_ids[right].clone(),
                    mode: mode.clone(),
                    queued_at: now,
                    metadata: HashMap::new(),
                };
                queued_matches.push(queued);
                if queued_matches.len() >= capped_max_pairs {
                    break 'outer;
                }
            }
        }

        let mut pending = self.inner.pending_matches.lock();
        let remaining_slots = MAX_ARENA_PENDING_MATCHES.saturating_sub(pending.len());
        let enqueue_count = queued_matches.len().min(remaining_slots);
        for queued in queued_matches.iter().take(enqueue_count) {
            pending.push_back(queued.clone());
        }
        let pending_total = pending.len();
        drop(pending);

        Ok(QueueMatchResponse {
            queued_count: enqueue_count,
            pending_total,
            queued_matches: queued_matches
                .iter()
                .take(enqueue_count)
                .map(to_queued_match_view)
                .collect(),
        })
    }

    fn claim_next_match(&self) -> ClaimMatchResponse {
        self.prune_stale_in_flight_matches();
        let maybe_claimed = {
            let mut pending = self.inner.pending_matches.lock();
            pending.pop_front()
        };

        if let Some(claimed) = maybe_claimed {
            self.inner
                .in_flight_matches
                .insert(claimed.match_id.clone(), claimed.clone());
            ClaimMatchResponse {
                claimed: Some(to_queued_match_view(&claimed)),
                pending_total: self.inner.pending_matches.lock().len(),
                in_flight_total: self.inner.in_flight_matches.len(),
            }
        } else {
            ClaimMatchResponse {
                claimed: None,
                pending_total: 0,
                in_flight_total: self.inner.in_flight_matches.len(),
            }
        }
    }

    fn list_pending_matches(&self, limit: usize) -> Vec<QueuedMatchView> {
        let bounded = limit.max(1);
        let pending = self.inner.pending_matches.lock();
        pending
            .iter()
            .take(bounded)
            .map(to_queued_match_view)
            .collect()
    }

    fn leaderboard(&self, limit: usize) -> ArenaLeaderboardResponse {
        let bounded_limit = limit.clamp(1, MAX_ARENA_LEADERBOARD_LIMIT);
        let store = self.inner.persistent_store.read();
        let mut models: Vec<ArenaModelView> = store.models.values().map(to_model_view).collect();
        models.sort_by(|left, right| {
            right
                .elo_rating
                .partial_cmp(&left.elo_rating)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| right.wins.cmp(&left.wins))
                .then_with(|| left.losses.cmp(&right.losses))
        });
        models.truncate(bounded_limit);

        ArenaLeaderboardResponse {
            generated_at: unix_now(),
            total_models: store.models.len(),
            total_completed_matches: store.completed_matches.len(),
            models,
        }
    }

    fn overview(&self) -> ArenaOverviewResponse {
        self.prune_stale_in_flight_matches();
        let store = self.inner.persistent_store.read();
        ArenaOverviewResponse {
            generated_at: unix_now(),
            active_models: store.models.values().filter(|model| model.active).count(),
            pending_matches: self.inner.pending_matches.lock().len(),
            in_flight_matches: self.inner.in_flight_matches.len(),
            total_completed_matches: store.completed_matches.len(),
            total_matches_reported_runtime: self
                .inner
                .total_matches_reported
                .load(Ordering::Relaxed),
        }
    }

    fn report_match(&self, body: ReportMatchBody) -> Result<ReportMatchResponse, ArenaError> {
        let match_id = body.match_id.trim();
        let in_flight = self.inner.in_flight_matches.remove(match_id);
        let pending_match = in_flight
            .map(|(_, value)| value)
            .or_else(|| {
                let mut pending = self.inner.pending_matches.lock();
                let idx = pending
                    .iter()
                    .position(|entry| entry.match_id == match_id)?;
                pending.remove(idx)
            })
            .ok_or_else(|| {
                ArenaError::NotFound(
                    "match_not_found",
                    format!(
                        "match '{}' was not found in pending/in-flight queue",
                        match_id
                    ),
                )
            })?;

        let model_a_id = body
            .model_a_id
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or(pending_match.model_a_id.as_str())
            .to_owned();
        let model_b_id = body
            .model_b_id
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or(pending_match.model_b_id.as_str())
            .to_owned();
        let draw = body.draw.unwrap_or(false);
        let winner_model_id = body
            .winner_model_id
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(ToOwned::to_owned);

        if !draw {
            if let Some(winner) = winner_model_id.as_deref() {
                if winner != model_a_id && winner != model_b_id {
                    return Err(ArenaError::InvalidInput(
                        "invalid_winner",
                        "winner_model_id must equal model_a_id or model_b_id".to_owned(),
                    ));
                }
            } else {
                return Err(ArenaError::InvalidInput(
                    "missing_winner",
                    "winner_model_id is required unless draw=true".to_owned(),
                ));
            }
        }

        let model_a_score = body.model_a_score.unwrap_or(0);
        let model_b_score = body.model_b_score.unwrap_or(0);
        let completed_at = unix_now();

        let model_a_result = if draw {
            MatchResult::Draw
        } else if winner_model_id.as_deref() == Some(model_a_id.as_str()) {
            MatchResult::Win
        } else {
            MatchResult::Loss
        };
        let model_b_result = model_a_result.inverse();

        let (model_a_view, model_b_view) = {
            let mut store = self.inner.persistent_store.write();
            let (model_a_old_elo, model_b_old_elo) = {
                let Some(model_a) = store.models.get(&model_a_id) else {
                    return Err(ArenaError::NotFound(
                        "model_not_found",
                        format!("model '{}' does not exist", model_a_id),
                    ));
                };
                let Some(model_b) = store.models.get(&model_b_id) else {
                    return Err(ArenaError::NotFound(
                        "model_not_found",
                        format!("model '{}' does not exist", model_b_id),
                    ));
                };
                (model_a.elo_rating, model_b.elo_rating)
            };
            let (new_a, new_b) = update_elo_pair(
                model_a_old_elo,
                model_b_old_elo,
                model_a_result,
                model_b_result,
            );

            {
                let Some(model_a) = store.models.get_mut(&model_a_id) else {
                    return Err(ArenaError::NotFound(
                        "model_not_found",
                        format!("model '{}' does not exist", model_a_id),
                    ));
                };
                apply_match_result(model_a, model_a_result, model_a_score, completed_at);
                model_a.elo_rating = new_a;
            }

            {
                let Some(model_b) = store.models.get_mut(&model_b_id) else {
                    return Err(ArenaError::NotFound(
                        "model_not_found",
                        format!("model '{}' does not exist", model_b_id),
                    ));
                };
                apply_match_result(model_b, model_b_result, model_b_score, completed_at);
                model_b.elo_rating = new_b;
            }

            store.completed_matches.push(CompletedMatchRecord {
                match_id: body.match_id.trim().to_owned(),
                model_a_id: model_a_id.clone(),
                model_b_id: model_b_id.clone(),
                winner_model_id: winner_model_id.clone(),
                draw,
                model_a_score,
                model_b_score,
                duration_ms: body.duration_ms,
                completed_at,
            });

            let model_a_view = store
                .models
                .get(&model_a_id)
                .map(to_model_view)
                .ok_or_else(|| {
                    ArenaError::Internal("post-report lookup failed for model_a".to_owned())
                })?;
            let model_b_view = store
                .models
                .get(&model_b_id)
                .map(to_model_view)
                .ok_or_else(|| {
                    ArenaError::Internal("post-report lookup failed for model_b".to_owned())
                })?;
            (model_a_view, model_b_view)
        };

        self.inner
            .total_matches_reported
            .fetch_add(1, Ordering::Relaxed);

        self.spawn_persist_store();

        Ok(ReportMatchResponse {
            match_id: body.match_id.trim().to_owned(),
            completed_at,
            model_a: model_a_view,
            model_b: model_b_view,
        })
    }

    fn execute_next_match(
        &self,
        body: ExecuteNextBody,
    ) -> Result<ExecuteNextMatchResponse, ArenaError> {
        let pending_before = self.inner.pending_matches.lock().len();
        let claimed = self.claim_next_match();
        let Some(claimed_match) = claimed.claimed else {
            return Err(ArenaError::NotFound(
                "no_pending_match",
                "no pending arena matches available for execution".to_owned(),
            ));
        };

        let seed = body.seed.unwrap_or_else(unix_now);
        let mode = ArenaMatchMode::parse(&claimed_match.mode).ok_or_else(|| {
            ArenaError::InvalidInput(
                "invalid_mode",
                format!("unsupported match mode '{}'", claimed_match.mode),
            )
        })?;
        let BotMatchExecution {
            outcome: sandbox_outcome,
            replay: sandbox_replay,
        } = self.inner.bot_sandbox.execute_match_with_replay(
            &claimed_match.model_a_id,
            &claimed_match.model_b_id,
            mode,
            seed,
            body.max_ticks,
        );

        let report = self.report_match(ReportMatchBody {
            match_id: claimed_match.match_id.clone(),
            model_a_id: Some(claimed_match.model_a_id.clone()),
            model_b_id: Some(claimed_match.model_b_id.clone()),
            winner_model_id: sandbox_outcome.winner_model_id.clone(),
            draw: Some(sandbox_outcome.draw),
            model_a_score: Some(sandbox_outcome.model_a_score),
            model_b_score: Some(sandbox_outcome.model_b_score),
            duration_ms: Some(sandbox_outcome.duration_ms),
        })?;

        self.push_recent_replay(ArenaReplayView {
            replay_id: format!(
                "replay_{:016x}",
                self.inner.replay_sequence.fetch_add(1, Ordering::Relaxed) + 1
            ),
            match_id: claimed_match.match_id.clone(),
            executed_at: report.completed_at,
            mode: sandbox_outcome.mode.clone(),
            model_a_id: claimed_match.model_a_id.clone(),
            model_b_id: claimed_match.model_b_id.clone(),
            winner_model_id: sandbox_outcome.winner_model_id.clone(),
            draw: sandbox_outcome.draw,
            model_a_score: sandbox_outcome.model_a_score,
            model_b_score: sandbox_outcome.model_b_score,
            objective_label: sandbox_outcome.objective_label.clone(),
            objective_a: sandbox_outcome.objective_a,
            objective_b: sandbox_outcome.objective_b,
            model_a_runtime: sandbox_outcome.model_a_runtime.clone(),
            model_b_runtime: sandbox_outcome.model_b_runtime.clone(),
            ticks_executed: sandbox_outcome.ticks_executed,
            duration_ms: sandbox_outcome.duration_ms,
            warnings: sandbox_outcome
                .warnings
                .iter()
                .take(MAX_ARENA_REPLAY_WARNINGS)
                .cloned()
                .collect(),
        });
        self.record_match_replay_events(
            &claimed_match,
            seed,
            report.completed_at,
            &sandbox_outcome,
            &sandbox_replay,
        );

        let pending_after = self.inner.pending_matches.lock().len();
        Ok(ExecuteNextMatchResponse {
            pending_before,
            pending_after,
            report,
            sandbox: sandbox_outcome,
        })
    }

    fn simulate_team_battle(
        &self,
        body: SimulateTeamBattleBody,
    ) -> Result<SimulateTeamBattleResponse, ArenaError> {
        let model_a_id = body.model_a_id.trim();
        let model_b_id = body.model_b_id.trim();
        if model_a_id.is_empty() || model_b_id.is_empty() {
            return Err(ArenaError::InvalidInput(
                "invalid_model_id",
                "model_a_id and model_b_id are required".to_owned(),
            ));
        }
        if model_a_id == model_b_id {
            return Err(ArenaError::InvalidInput(
                "invalid_matchup",
                "model_a_id and model_b_id must be different".to_owned(),
            ));
        }

        let store = self.inner.persistent_store.read();
        if !store.models.contains_key(model_a_id) {
            return Err(ArenaError::NotFound(
                "model_not_found",
                format!("model '{}' does not exist", model_a_id),
            ));
        }
        if !store.models.contains_key(model_b_id) {
            return Err(ArenaError::NotFound(
                "model_not_found",
                format!("model '{}' does not exist", model_b_id),
            ));
        }
        drop(store);

        let mode = normalize_match_mode(body.mode.as_deref())?;
        let mode = ArenaMatchMode::parse(&mode).ok_or_else(|| {
            ArenaError::InvalidInput("invalid_mode", format!("unsupported match mode '{}'", mode))
        })?;
        let team_size = body.team_size.unwrap_or(10);
        let rounds = body.rounds.unwrap_or(1);
        let seed = body.seed.unwrap_or_else(unix_now);

        let simulation = self.inner.bot_sandbox.execute_team_battle(
            model_a_id,
            model_b_id,
            mode,
            team_size,
            rounds,
            seed,
            body.max_ticks,
        );

        Ok(SimulateTeamBattleResponse {
            generated_at: unix_now(),
            simulation,
        })
    }

    pub fn worker_execute_next(
        &self,
        max_ticks: Option<u32>,
        seed: Option<u64>,
    ) -> Result<Option<ExecuteNextMatchResponse>, String> {
        self.inner.worker_runs.fetch_add(1, Ordering::Relaxed);
        match self.execute_next_match(ExecuteNextBody { max_ticks, seed }) {
            Ok(response) => {
                self.inner.worker_executed.fetch_add(1, Ordering::Relaxed);
                self.record_worker_success_metrics(&response);
                self.inner
                    .worker_last_success_at
                    .store(unix_now(), Ordering::Relaxed);
                *self.inner.worker_last_error.write() = None;
                Ok(Some(response))
            }
            Err(ArenaError::NotFound("no_pending_match", _)) => {
                self.inner.worker_idle.fetch_add(1, Ordering::Relaxed);
                Ok(None)
            }
            Err(err) => {
                self.inner.worker_failures.fetch_add(1, Ordering::Relaxed);
                self.inner
                    .worker_last_failure_at
                    .store(unix_now(), Ordering::Relaxed);
                let message = err.message();
                *self.inner.worker_last_error.write() = Some(message.clone());
                Err(message)
            }
        }
    }

    pub fn worker_stats(&self) -> ArenaWorkerStatsResponse {
        let last_success_raw = self.inner.worker_last_success_at.load(Ordering::Relaxed);
        let last_failure_raw = self.inner.worker_last_failure_at.load(Ordering::Relaxed);
        let executed = self.inner.worker_executed.load(Ordering::Relaxed);
        let total_duration_ms = self.inner.worker_total_duration_ms.load(Ordering::Relaxed);
        let total_ticks = self.inner.worker_total_ticks.load(Ordering::Relaxed);
        let min_duration_raw = self.inner.worker_min_duration_ms.load(Ordering::Relaxed);
        ArenaWorkerStatsResponse {
            generated_at: unix_now(),
            pending_matches: self.inner.pending_matches.lock().len(),
            in_flight_matches: self.inner.in_flight_matches.len(),
            runs: self.inner.worker_runs.load(Ordering::Relaxed),
            executed,
            idle: self.inner.worker_idle.load(Ordering::Relaxed),
            failures: self.inner.worker_failures.load(Ordering::Relaxed),
            last_success_at: (last_success_raw > 0).then_some(last_success_raw),
            last_failure_at: (last_failure_raw > 0).then_some(last_failure_raw),
            last_error: self.inner.worker_last_error.read().clone(),
            total_match_duration_ms: total_duration_ms,
            avg_match_duration_ms: safe_average(total_duration_ms, executed),
            max_match_duration_ms: self.inner.worker_max_duration_ms.load(Ordering::Relaxed),
            min_match_duration_ms: (min_duration_raw > 0).then_some(min_duration_raw),
            total_ticks_executed: total_ticks,
            avg_ticks_executed: safe_average(total_ticks, executed),
            warning_matches: self.inner.worker_warning_matches.load(Ordering::Relaxed),
            runtime_fallback_matches: self
                .inner
                .worker_runtime_fallback_matches
                .load(Ordering::Relaxed),
            trap_warnings: self.inner.worker_trap_warnings.load(Ordering::Relaxed),
            timeout_warnings: self.inner.worker_timeout_warnings.load(Ordering::Relaxed),
            draw_matches: self.inner.worker_draw_matches.load(Ordering::Relaxed),
            model_win_distribution: self.inner.worker_model_win_distribution.read().clone(),
        }
    }

    fn recent_replays(&self, limit: usize) -> ArenaReplayListResponse {
        let bounded = limit.clamp(1, 200);
        let history = self.inner.recent_replays.lock();
        let replays = history.iter().rev().take(bounded).cloned().collect();
        ArenaReplayListResponse {
            generated_at: unix_now(),
            total_replays: history.len(),
            replays,
        }
    }

    fn push_recent_replay(&self, replay: ArenaReplayView) {
        let mut history = self.inner.recent_replays.lock();
        while history.len() >= self.inner.replay_history_capacity {
            history.pop_front();
        }
        history.push_back(replay);
    }

    fn next_replay_event_sequence(&self) -> u64 {
        self.inner
            .replay_event_sequence
            .fetch_add(1, Ordering::Relaxed)
            + 1
    }

    fn push_replay_event(&self, event: ArenaReplayEvent) {
        {
            let mut replay_events = self.inner.replay_events.lock();
            while replay_events.len() >= self.inner.replay_event_history_capacity {
                replay_events.pop_front();
            }
            replay_events.push_back(event.clone());
        }
        let _ = self.inner.replay_event_tx.send(event);
    }

    fn record_match_replay_events(
        &self,
        queued_match: &QueuedMatchView,
        seed: u64,
        completed_at: u64,
        outcome: &BotMatchOutcome,
        replay: &BotMatchReplay,
    ) {
        let mut events = Vec::with_capacity(replay.frames.len().saturating_add(2));
        let start_event = ArenaReplayEvent {
            sequence: self.next_replay_event_sequence(),
            emitted_at: completed_at,
            match_id: queued_match.match_id.clone(),
            mode: outcome.mode.clone(),
            event_type: "match_start".to_owned(),
            tick: Some(0),
            action_model_a: None,
            action_model_b: None,
            health_model_a: None,
            health_model_b: None,
            score_model_a: Some(0),
            score_model_b: Some(0),
            objective_a: Some(0),
            objective_b: Some(0),
            winner_model_id: None,
            draw: None,
            duration_ms: None,
        };
        self.push_replay_event(start_event.clone());
        events.push(start_event);

        for frame in &replay.frames {
            let tick_event = ArenaReplayEvent {
                sequence: self.next_replay_event_sequence(),
                emitted_at: completed_at,
                match_id: queued_match.match_id.clone(),
                mode: outcome.mode.clone(),
                event_type: "tick".to_owned(),
                tick: Some(frame.tick),
                action_model_a: Some(frame.action_model_a.clone()),
                action_model_b: Some(frame.action_model_b.clone()),
                health_model_a: Some(frame.health_model_a),
                health_model_b: Some(frame.health_model_b),
                score_model_a: Some(frame.score_model_a),
                score_model_b: Some(frame.score_model_b),
                objective_a: Some(frame.objective_a),
                objective_b: Some(frame.objective_b),
                winner_model_id: None,
                draw: None,
                duration_ms: None,
            };
            self.push_replay_event(tick_event.clone());
            events.push(tick_event);
        }

        let completed_event = ArenaReplayEvent {
            sequence: self.next_replay_event_sequence(),
            emitted_at: completed_at,
            match_id: queued_match.match_id.clone(),
            mode: outcome.mode.clone(),
            event_type: if outcome.draw {
                "match_draw".to_owned()
            } else {
                "match_end".to_owned()
            },
            tick: Some(outcome.ticks_executed),
            action_model_a: None,
            action_model_b: None,
            health_model_a: None,
            health_model_b: None,
            score_model_a: Some(outcome.model_a_score),
            score_model_b: Some(outcome.model_b_score),
            objective_a: Some(outcome.objective_a),
            objective_b: Some(outcome.objective_b),
            winner_model_id: outcome.winner_model_id.clone(),
            draw: Some(outcome.draw),
            duration_ms: Some(outcome.duration_ms),
        };
        self.push_replay_event(completed_event.clone());
        events.push(completed_event);

        let replay_record = ArenaMatchReplayRecord {
            match_id: queued_match.match_id.clone(),
            mode: outcome.mode.clone(),
            model_a_id: queued_match.model_a_id.clone(),
            model_b_id: queued_match.model_b_id.clone(),
            seed,
            max_ticks: replay.max_ticks,
            ticks_executed: outcome.ticks_executed,
            duration_ms: outcome.duration_ms,
            winner_model_id: outcome.winner_model_id.clone(),
            draw: outcome.draw,
            warnings: outcome
                .warnings
                .iter()
                .take(MAX_ARENA_REPLAY_WARNINGS)
                .cloned()
                .collect(),
            truncated: replay.truncated,
            total_frames: replay.total_ticks_executed as usize,
            completed_at,
            events,
        };

        let mut replay_match_order = self.inner.replay_match_order.lock();
        let mut replay_matches = self.inner.replay_matches.write();
        if !replay_matches.contains_key(&queued_match.match_id) {
            replay_match_order.push_back(queued_match.match_id.clone());
        }
        replay_matches.insert(queued_match.match_id.clone(), replay_record);
        while replay_match_order.len() > self.inner.replay_match_history_capacity {
            if let Some(evicted_match_id) = replay_match_order.pop_front() {
                replay_matches.remove(&evicted_match_id);
            }
        }
    }

    fn recent_replay_events(
        &self,
        limit: usize,
        after_sequence: Option<u64>,
    ) -> ArenaReplayEventFeedResponse {
        let bounded_limit = limit.clamp(1, MAX_ARENA_REPLAY_EVENTS_LIMIT);
        let after = after_sequence.unwrap_or(0);
        let replay_events = self.inner.replay_events.lock();
        let mut filtered: Vec<ArenaReplayEvent> = replay_events
            .iter()
            .filter(|event| event.sequence > after)
            .cloned()
            .collect();
        if filtered.len() > bounded_limit {
            let truncate_from = filtered.len() - bounded_limit;
            filtered.drain(0..truncate_from);
        }
        let newest_sequence = filtered.last().map(|event| event.sequence);
        ArenaReplayEventFeedResponse {
            generated_at: unix_now(),
            total_events: replay_events.len(),
            returned_events: filtered.len(),
            newest_sequence,
            events: filtered,
        }
    }

    fn replay_events_for_match(
        &self,
        match_id: &str,
        limit: usize,
        after_sequence: Option<u64>,
    ) -> Result<ArenaMatchReplayResponse, ArenaError> {
        let bounded_limit = limit.clamp(1, MAX_ARENA_REPLAY_EVENTS_LIMIT);
        let after = after_sequence.unwrap_or(0);
        let record = self
            .inner
            .replay_matches
            .read()
            .get(match_id)
            .cloned()
            .ok_or_else(|| {
                ArenaError::NotFound(
                    "replay_not_found",
                    format!("replay for match '{}' was not found", match_id),
                )
            })?;

        let mut filtered: Vec<ArenaReplayEvent> = record
            .events
            .iter()
            .filter(|event| event.sequence > after)
            .cloned()
            .collect();
        if filtered.len() > bounded_limit {
            let truncate_from = filtered.len() - bounded_limit;
            filtered.drain(0..truncate_from);
        }
        let returned_events = filtered.len();

        Ok(ArenaMatchReplayResponse {
            generated_at: unix_now(),
            match_id: record.match_id,
            mode: record.mode,
            model_a_id: record.model_a_id,
            model_b_id: record.model_b_id,
            seed: record.seed,
            max_ticks: record.max_ticks,
            ticks_executed: record.ticks_executed,
            duration_ms: record.duration_ms,
            winner_model_id: record.winner_model_id,
            draw: record.draw,
            truncated: record.truncated,
            total_frames: record.total_frames,
            total_events: record.events.len(),
            returned_events,
            completed_at: record.completed_at,
            warnings: record.warnings,
            events: filtered,
        })
    }

    fn replay_stream(&self, query: ReplayStreamQuery) -> impl Reply {
        let after_sequence = query.after_sequence.unwrap_or(0);
        let backlog_limit = query
            .backlog
            .unwrap_or(DEFAULT_ARENA_REPLAY_STREAM_BACKLOG)
            .clamp(0, MAX_ARENA_STREAM_BACKLOG);
        let backlog_events = if backlog_limit == 0 {
            Vec::new()
        } else {
            self.recent_replay_events(backlog_limit, Some(after_sequence))
                .events
        };
        let receiver = self.inner.replay_event_tx.subscribe();
        let backlog_stream = stream::iter(
            backlog_events
                .into_iter()
                .map(arena_replay_event_to_sse_result),
        );
        let live_stream = BroadcastStream::new(receiver).filter_map(move |result| async move {
            match result {
                Ok(event) if event.sequence > after_sequence => {
                    Some(arena_replay_event_to_sse_result(event))
                }
                Ok(_) => None,
                Err(tokio_stream::wrappers::errors::BroadcastStreamRecvError::Lagged(skipped)) => {
                    let lag_event = warp::sse::Event::default()
                        .event("lagged")
                        .data(format!("lagged:{}", skipped));
                    Some(Ok(lag_event))
                }
            }
        });
        let event_stream = backlog_stream.chain(live_stream);
        warp::sse::reply(
            warp::sse::keep_alive()
                .interval(Duration::from_secs(10))
                .text("keepalive")
                .stream(event_stream),
        )
    }

    fn record_worker_success_metrics(&self, response: &ExecuteNextMatchResponse) {
        let sandbox = &response.sandbox;
        let duration_ms = sandbox.duration_ms;
        let ticks = sandbox.ticks_executed as u64;

        self.inner
            .worker_total_duration_ms
            .fetch_add(duration_ms, Ordering::Relaxed);
        self.inner
            .worker_total_ticks
            .fetch_add(ticks, Ordering::Relaxed);
        atomic_update_max(&self.inner.worker_max_duration_ms, duration_ms);
        atomic_update_min_nonzero(&self.inner.worker_min_duration_ms, duration_ms);

        if !sandbox.warnings.is_empty() {
            self.inner
                .worker_warning_matches
                .fetch_add(1, Ordering::Relaxed);
        }
        if sandbox.draw {
            self.inner
                .worker_draw_matches
                .fetch_add(1, Ordering::Relaxed);
        }
        if sandbox.model_a_runtime == "fallback" || sandbox.model_b_runtime == "fallback" {
            self.inner
                .worker_runtime_fallback_matches
                .fetch_add(1, Ordering::Relaxed);
        }
        if let Some(winner) = sandbox.winner_model_id.as_ref() {
            let mut distribution = self.inner.worker_model_win_distribution.write();
            *distribution.entry(winner.clone()).or_insert(0) += 1;
        }

        let mut trap_warnings = 0u64;
        let mut timeout_warnings = 0u64;
        for warning in &sandbox.warnings {
            let normalized = warning.to_ascii_lowercase();
            if normalized.contains("trap") {
                trap_warnings = trap_warnings.saturating_add(1);
            }
            if normalized.contains("timeout") || normalized.contains("fuel") {
                timeout_warnings = timeout_warnings.saturating_add(1);
            }
        }
        if trap_warnings > 0 {
            self.inner
                .worker_trap_warnings
                .fetch_add(trap_warnings, Ordering::Relaxed);
        }
        if timeout_warnings > 0 {
            self.inner
                .worker_timeout_warnings
                .fetch_add(timeout_warnings, Ordering::Relaxed);
        }
    }

    fn get_model_view(&self, model_id: &str) -> Option<ArenaModelView> {
        let store = self.inner.persistent_store.read();
        store.models.get(model_id).map(to_model_view)
    }

    /// Offloads arena store persistence to a blocking thread so that
    /// tokio worker threads are not stalled by file I/O.
    /// Falls back to synchronous persistence when no tokio runtime is
    /// available (e.g. in unit tests).
    fn spawn_persist_store(&self) {
        let snapshot = {
            let store = self.inner.persistent_store.read();
            store.clone()
        };
        let path = self.inner.store_path.clone();
        let do_persist = move || {
            if let Err(err) = persist_store(&path, &snapshot) {
                warn!("Background arena persist failed: {}", err);
            }
        };
        if tokio::runtime::Handle::try_current().is_ok() {
            tokio::task::spawn_blocking(do_persist);
        } else {
            do_persist();
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MatchResult {
    Win,
    Loss,
    Draw,
}

impl MatchResult {
    fn score(self) -> f64 {
        match self {
            MatchResult::Win => 1.0,
            MatchResult::Loss => 0.0,
            MatchResult::Draw => 0.5,
        }
    }

    fn inverse(self) -> MatchResult {
        match self {
            MatchResult::Win => MatchResult::Loss,
            MatchResult::Loss => MatchResult::Win,
            MatchResult::Draw => MatchResult::Draw,
        }
    }
}

fn safe_average(total: u64, count: u64) -> f64 {
    if count == 0 {
        0.0
    } else {
        total as f64 / count as f64
    }
}

fn atomic_update_max(counter: &AtomicU64, value: u64) {
    loop {
        let current = counter.load(Ordering::Relaxed);
        if value <= current {
            return;
        }
        if counter
            .compare_exchange(current, value, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            return;
        }
    }
}

fn atomic_update_min_nonzero(counter: &AtomicU64, value: u64) {
    if value == 0 {
        return;
    }
    loop {
        let current = counter.load(Ordering::Relaxed);
        if current != 0 && value >= current {
            return;
        }
        if counter
            .compare_exchange(current, value, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            return;
        }
    }
}

fn apply_match_result(
    model: &mut ArenaModelRecord,
    result: MatchResult,
    score: i32,
    completed_at: u64,
) {
    model.matches_played = model.matches_played.saturating_add(1);
    match result {
        MatchResult::Win => model.wins = model.wins.saturating_add(1),
        MatchResult::Loss => model.losses = model.losses.saturating_add(1),
        MatchResult::Draw => model.draws = model.draws.saturating_add(1),
    }
    model.cumulative_score = model.cumulative_score.saturating_add(score as i64);
    model.updated_at = completed_at;
    model.last_seen_at = completed_at;
}

fn update_elo_pair(
    elo_a: f64,
    elo_b: f64,
    result_a: MatchResult,
    result_b: MatchResult,
) -> (f64, f64) {
    let expected_a = 1.0 / (1.0 + 10.0f64.powf((elo_b - elo_a) / 400.0));
    let expected_b = 1.0 / (1.0 + 10.0f64.powf((elo_a - elo_b) / 400.0));
    let k = 32.0;
    let updated_a = (elo_a + k * (result_a.score() - expected_a)).clamp(100.0, 4000.0);
    let updated_b = (elo_b + k * (result_b.score() - expected_b)).clamp(100.0, 4000.0);
    (updated_a, updated_b)
}

fn to_model_view(model: &ArenaModelRecord) -> ArenaModelView {
    let win_rate = if model.matches_played == 0 {
        0.0
    } else {
        model.wins as f64 / model.matches_played as f64
    };

    ArenaModelView {
        model_id: model.model_id.clone(),
        model_name: model.model_name.clone(),
        provider: model.provider.clone(),
        version: model.version.clone(),
        active: model.active,
        elo_rating: model.elo_rating,
        matches_played: model.matches_played,
        wins: model.wins,
        losses: model.losses,
        draws: model.draws,
        cumulative_score: model.cumulative_score,
        win_rate,
        created_at: model.created_at,
        updated_at: model.updated_at,
        last_seen_at: model.last_seen_at,
    }
}

fn to_queued_match_view(entry: &QueuedMatch) -> QueuedMatchView {
    QueuedMatchView {
        match_id: entry.match_id.clone(),
        model_a_id: entry.model_a_id.clone(),
        model_b_id: entry.model_b_id.clone(),
        mode: entry.mode.clone(),
        queued_at: entry.queued_at,
    }
}

fn normalize_match_mode(raw_mode: Option<&str>) -> Result<String, ArenaError> {
    let value = raw_mode
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .unwrap_or("arena");
    let Some(mode) = ArenaMatchMode::parse(value) else {
        return Err(ArenaError::InvalidInput(
            "invalid_mode",
            format!(
                "unsupported mode '{}'; expected one of: arena, ctf, koth, tdm",
                value
            ),
        ));
    };
    Ok(mode.as_str().to_owned())
}

fn sanitize_model_id(model_id: &str) -> Option<String> {
    let trimmed = model_id.trim();
    if trimmed.is_empty() || trimmed.len() > MAX_MODEL_ID_LEN {
        return None;
    }
    if trimmed.starts_with('.') || trimmed.ends_with('.') || trimmed.contains("..") {
        return None;
    }
    if trimmed
        .bytes()
        .all(|ch| ch.is_ascii_alphanumeric() || ch == b'_' || ch == b'-' || ch == b'.')
    {
        Some(trimmed.to_owned())
    } else {
        None
    }
}

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0)
}

fn load_persistent_store(path: &Path) -> PersistentArenaStore {
    let raw = match fs::read_to_string(path) {
        Ok(raw) => raw,
        Err(err) => {
            if err.kind() != std::io::ErrorKind::NotFound {
                warn!("Failed to read arena store '{}': {}", path.display(), err);
            }
            return PersistentArenaStore::default();
        }
    };

    serde_json::from_str(&raw).unwrap_or_else(|err| {
        warn!(
            "Failed to parse arena store '{}': {}. Starting with empty arena store.",
            path.display(),
            err
        );
        PersistentArenaStore::default()
    })
}

fn persist_store(path: &Path, store: &PersistentArenaStore) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|err| format!("failed to create '{}': {}", parent.display(), err))?;
    }
    let serialized = serde_json::to_string_pretty(store)
        .map_err(|err| format!("failed to serialize arena store: {}", err))?;
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("arena_store.json");
    let tmp_path = path.with_file_name(format!(".{}.{}.tmp", file_name, Uuid::new_v4().simple()));
    let mut tmp_file = fs::File::create(&tmp_path)
        .map_err(|err| format!("failed to create '{}': {}", tmp_path.display(), err))?;
    tmp_file
        .write_all(serialized.as_bytes())
        .map_err(|err| format!("failed to write '{}': {}", tmp_path.display(), err))?;
    tmp_file
        .sync_all()
        .map_err(|err| format!("failed to fsync '{}': {}", tmp_path.display(), err))?;
    fs::rename(&tmp_path, path).map_err(|err| {
        format!(
            "failed to atomically replace '{}' with '{}': {}",
            path.display(),
            tmp_path.display(),
            err
        )
    })?;
    Ok(())
}

fn arena_replay_event_to_sse_result(
    event: ArenaReplayEvent,
) -> Result<warp::sse::Event, Infallible> {
    let event_name = event.event_type.clone();
    let event_id = event.sequence.to_string();
    let sse_event = match warp::sse::Event::default()
        .id(event_id)
        .event(event_name)
        .json_data(&event)
    {
        Ok(sse_event) => sse_event,
        Err(_) => warp::sse::Event::default()
            .event("encode_error")
            .data("{\"error\":\"failed to encode replay event\"}"),
    };
    Ok(sse_event)
}

fn ok_response<T>(data: T) -> warp::reply::Json
where
    T: Serialize,
{
    warp::reply::json(&ApiResponse {
        ok: true,
        data: Some(data),
        error: None::<ApiErrorBody>,
    })
}

fn error_response(code: &'static str, message: String) -> warp::reply::Json {
    warp::reply::json(&ApiResponse::<serde_json::Value> {
        ok: false,
        data: None,
        error: Some(ApiErrorBody { code, message }),
    })
}

fn with_service(
    service: ArenaService,
) -> impl Filter<Extract = (ArenaService,), Error = std::convert::Infallible> + Clone {
    warp::any().map(move || service.clone())
}

fn inline_admin_expected_token() -> Option<&'static String> {
    static TOKEN: OnceLock<Option<String>> = OnceLock::new();
    TOKEN
        .get_or_init(|| {
            std::env::var("MGS_ADMIN_BEARER_TOKEN")
                .or_else(|_| std::env::var("MGS_ADMIN_TOKEN"))
                .ok()
                .map(|raw| raw.trim().to_owned())
                .filter(|raw| !raw.is_empty())
        })
        .as_ref()
}

fn parse_bearer_token(authorization_header: Option<&str>) -> Option<&str> {
    let raw = authorization_header?.trim();
    if raw.is_empty() {
        return None;
    }
    raw.strip_prefix("Bearer ")
        .or_else(|| raw.strip_prefix("bearer "))
        .map(str::trim)
        .filter(|token| !token.is_empty())
}

fn constant_time_eq(left: &str, right: &str) -> bool {
    let left_bytes = left.as_bytes();
    let right_bytes = right.as_bytes();
    left_bytes.len() == right_bytes.len() && left_bytes.ct_eq(right_bytes).into()
}

fn inline_admin_authorized(authorization_header: Option<&str>) -> bool {
    let Some(expected) = inline_admin_expected_token() else {
        return false;
    };
    let Some(provided) = parse_bearer_token(authorization_header) else {
        return false;
    };
    constant_time_eq(expected.as_str(), provided)
}

pub fn build_arena_routes(
    service: ArenaService,
) -> impl Filter<Extract = (impl Reply,), Error = warp::Rejection> + Clone {
    // 64 KB body limit for standard JSON endpoints; upload_wasm uses a larger
    // limit since base64-encoded wasm can be up to ~2.7 MB (2 MB decoded).
    let json_body_limit = 1024 * 64;
    let wasm_upload_body_limit = 4 * 1024 * 1024; // 4 MB for base64-encoded wasm

    let register_model = warp::path!("api" / "arena" / "models" / "register")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(warp::body::content_length_limit(json_body_limit))
        .and(warp::body::json())
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: RegisterModelBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.register_model(body) {
                    Ok(model) => ok_response(model),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let model_heartbeat = warp::path!("api" / "arena" / "models" / "heartbeat")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(warp::body::content_length_limit(json_body_limit))
        .and(warp::body::json())
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: ModelHeartbeatBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.heartbeat_model(body) {
                    Ok(model) => ok_response(model),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let upload_model_wasm = warp::path!("api" / "arena" / "models" / "upload_wasm")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(warp::body::content_length_limit(wasm_upload_body_limit))
        .and(warp::body::json())
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: UploadModelWasmBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.upload_model_wasm(body) {
                    Ok(result) => ok_response(result),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let list_models = warp::path!("api" / "arena" / "models")
        .and(warp::get())
        .and(
            warp::query::<LeaderboardQuery>()
                .or(warp::any().map(LeaderboardQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(|query: LeaderboardQuery, arena: ArenaService| {
            let limit = query.limit.unwrap_or(DEFAULT_ARENA_LEADERBOARD_LIMIT);
            let leaderboard = arena.leaderboard(limit);
            ok_response(leaderboard.models)
        });

    let queue_match = warp::path!("api" / "arena" / "matches" / "queue")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(warp::body::content_length_limit(json_body_limit))
        .and(warp::body::json())
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: QueueMatchBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.queue_match(body) {
                    Ok(result) => ok_response(result),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let queue_round_robin = warp::path!("api" / "arena" / "matches" / "queue_round_robin")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(warp::body::content_length_limit(json_body_limit))
        .and(warp::body::json())
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: QueueRoundRobinBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.queue_round_robin(body) {
                    Ok(result) => ok_response(result),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let claim_next = warp::path!("api" / "arena" / "matches" / "claim_next")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(with_service(service.clone()))
        .map(|authorization: Option<String>, arena: ArenaService| {
            if !inline_admin_authorized(authorization.as_deref()) {
                return error_response(
                    "admin_auth_required",
                    "Admin bearer token required.".to_owned(),
                );
            }
            ok_response(arena.claim_next_match())
        });

    let execute_next = warp::path!("api" / "arena" / "matches" / "execute_next")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(
            warp::body::content_length_limit(json_body_limit)
                .and(warp::body::json::<ExecuteNextBody>())
                .or(warp::any().map(ExecuteNextBody::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: ExecuteNextBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.execute_next_match(body) {
                    Ok(result) => ok_response(result),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let simulate_team_battle = warp::path!("api" / "arena" / "matches" / "simulate_team_battle")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(
            warp::body::content_length_limit(json_body_limit)
                .and(warp::body::json::<SimulateTeamBattleBody>())
                .or(warp::any().map(SimulateTeamBattleBody::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: SimulateTeamBattleBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.simulate_team_battle(body) {
                    Ok(result) => ok_response(result),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let list_pending = warp::path!("api" / "arena" / "matches" / "pending")
        .and(warp::get())
        .and(
            warp::query::<PendingQuery>()
                .or(warp::any().map(PendingQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(|query: PendingQuery, arena: ArenaService| {
            let limit = query.limit.unwrap_or(DEFAULT_ARENA_PENDING_LIMIT);
            ok_response(arena.list_pending_matches(limit))
        });

    let recent_replays = warp::path!("api" / "arena" / "replays" / "recent")
        .and(warp::get())
        .and(
            warp::query::<ReplayQuery>()
                .or(warp::any().map(ReplayQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(|query: ReplayQuery, arena: ArenaService| {
            let limit = query.limit.unwrap_or(DEFAULT_ARENA_RECENT_REPLAY_LIMIT);
            ok_response(arena.recent_replays(limit))
        });

    let replay_events_recent = warp::path!("api" / "arena" / "replays" / "events" / "recent")
        .and(warp::get())
        .and(
            warp::query::<ReplayEventsQuery>()
                .or(warp::any().map(ReplayEventsQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(|query: ReplayEventsQuery, arena: ArenaService| {
            let limit = query.limit.unwrap_or(DEFAULT_ARENA_REPLAY_EVENTS_LIMIT);
            ok_response(arena.recent_replay_events(limit, query.after_sequence))
        });

    let replay_events_for_match = warp::path!("api" / "arena" / "replays" / String / "events")
        .and(warp::get())
        .and(
            warp::query::<ReplayEventsQuery>()
                .or(warp::any().map(ReplayEventsQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(
            |match_id: String, query: ReplayEventsQuery, arena: ArenaService| {
                let limit = query.limit.unwrap_or(DEFAULT_ARENA_REPLAY_EVENTS_LIMIT);
                match arena.replay_events_for_match(&match_id, limit, query.after_sequence) {
                    Ok(response) => ok_response(response),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let replay_stream = warp::path!("api" / "arena" / "replays" / "stream")
        .and(warp::get())
        .and(
            warp::query::<ReplayStreamQuery>()
                .or(warp::any().map(ReplayStreamQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(|query: ReplayStreamQuery, arena: ArenaService| arena.replay_stream(query));

    let report_match = warp::path!("api" / "arena" / "matches" / "report")
        .and(warp::post())
        .and(warp::header::optional::<String>("authorization"))
        .and(warp::body::content_length_limit(json_body_limit))
        .and(warp::body::json())
        .and(with_service(service.clone()))
        .map(
            |authorization: Option<String>, body: ReportMatchBody, arena: ArenaService| {
                if !inline_admin_authorized(authorization.as_deref()) {
                    return error_response(
                        "admin_auth_required",
                        "Admin bearer token required.".to_owned(),
                    );
                }
                match arena.report_match(body) {
                    Ok(result) => ok_response(result),
                    Err(err) => error_response(err.code(), err.message()),
                }
            },
        );

    let leaderboard = warp::path!("api" / "arena" / "leaderboard")
        .and(warp::get())
        .and(
            warp::query::<LeaderboardQuery>()
                .or(warp::any().map(LeaderboardQuery::default))
                .unify(),
        )
        .and(with_service(service.clone()))
        .map(|query: LeaderboardQuery, arena: ArenaService| {
            let limit = query.limit.unwrap_or(DEFAULT_ARENA_LEADERBOARD_LIMIT);
            ok_response(arena.leaderboard(limit))
        });

    let overview = warp::path!("api" / "arena" / "overview")
        .and(warp::get())
        .and(with_service(service.clone()))
        .map(|arena: ArenaService| ok_response(arena.overview()));

    let worker_stats = warp::path!("api" / "arena" / "worker" / "stats")
        .and(warp::get())
        .and(with_service(service))
        .map(|arena: ArenaService| ok_response(arena.worker_stats()));

    register_model
        .or(model_heartbeat)
        .or(upload_model_wasm)
        .or(list_models)
        .or(queue_match)
        .or(queue_round_robin)
        .or(claim_next)
        .or(execute_next)
        .or(simulate_team_battle)
        .or(list_pending)
        .or(recent_replays)
        .or(replay_events_recent)
        .or(replay_events_for_match)
        .or(replay_stream)
        .or(report_match)
        .or(leaderboard)
        .or(overview)
        .or(worker_stats)
        .map(warp::reply::Reply::into_response)
        .boxed()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn elo_updates_are_conservative() {
        let (new_a, new_b) = update_elo_pair(1000.0, 1000.0, MatchResult::Win, MatchResult::Loss);
        assert!(new_a > 1000.0);
        assert!(new_b < 1000.0);
        let delta_a = new_a - 1000.0;
        let delta_b = 1000.0 - new_b;
        assert!((delta_a - delta_b).abs() < 0.001);
    }

    #[test]
    fn round_robin_limits_pairs() {
        let service = ArenaService {
            inner: Arc::new(ArenaInner {
                store_path: PathBuf::from("/tmp/test_arena_store_unused.json"),
                bot_sandbox: BotSandbox::new_from_env(),
                wasm_dir: PathBuf::from("/tmp/test_arena_wasm"),
                wasm_max_bytes: DEFAULT_ARENA_WASM_MAX_BYTES,
                persistent_store: RwLock::new(PersistentArenaStore {
                    models: HashMap::from([
                        (
                            "a".to_owned(),
                            ArenaModelRecord {
                                model_id: "a".to_owned(),
                                model_name: "a".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                        (
                            "b".to_owned(),
                            ArenaModelRecord {
                                model_id: "b".to_owned(),
                                model_name: "b".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                        (
                            "c".to_owned(),
                            ArenaModelRecord {
                                model_id: "c".to_owned(),
                                model_name: "c".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                    ]),
                    completed_matches: Vec::new(),
                }),
                pending_matches: Mutex::new(VecDeque::new()),
                in_flight_matches: DashMap::new(),
                total_matches_reported: AtomicU64::new(0),
                worker_runs: AtomicU64::new(0),
                worker_executed: AtomicU64::new(0),
                worker_idle: AtomicU64::new(0),
                worker_failures: AtomicU64::new(0),
                worker_last_success_at: AtomicU64::new(0),
                worker_last_failure_at: AtomicU64::new(0),
                worker_last_error: RwLock::new(None),
                worker_total_duration_ms: AtomicU64::new(0),
                worker_total_ticks: AtomicU64::new(0),
                worker_warning_matches: AtomicU64::new(0),
                worker_runtime_fallback_matches: AtomicU64::new(0),
                worker_trap_warnings: AtomicU64::new(0),
                worker_timeout_warnings: AtomicU64::new(0),
                worker_draw_matches: AtomicU64::new(0),
                worker_max_duration_ms: AtomicU64::new(0),
                worker_min_duration_ms: AtomicU64::new(0),
                worker_model_win_distribution: RwLock::new(HashMap::new()),
                replay_sequence: AtomicU64::new(0),
                replay_history_capacity: DEFAULT_ARENA_REPLAY_HISTORY_CAP,
                recent_replays: Mutex::new(VecDeque::new()),
                replay_event_sequence: AtomicU64::new(0),
                replay_event_history_capacity: DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP,
                replay_match_history_capacity: DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP,
                replay_events: Mutex::new(VecDeque::new()),
                replay_match_order: Mutex::new(VecDeque::new()),
                replay_matches: RwLock::new(HashMap::new()),
                replay_event_tx: broadcast::channel(DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP).0,
            }),
        };

        let result = service
            .queue_round_robin(QueueRoundRobinBody {
                mode: Some("TEAM_DEATHMATCH".to_owned()),
                include_inactive: Some(false),
                max_pairs: Some(2),
            })
            .expect("round robin should queue");
        assert_eq!(result.queued_count, 2);
        assert!(result
            .queued_matches
            .iter()
            .all(|entry| entry.mode == "tdm"));
    }

    #[test]
    fn sanitize_model_id_rejects_hidden_and_traversal_like_names() {
        assert!(sanitize_model_id("../etc/passwd").is_none());
        assert!(sanitize_model_id(".hidden-model").is_none());
        assert!(sanitize_model_id("model..double-dot").is_none());
        assert!(sanitize_model_id("bot-alpha_1").is_some());
    }

    #[test]
    fn execute_next_match_reports_result() {
        let service = ArenaService {
            inner: Arc::new(ArenaInner {
                store_path: PathBuf::from("/tmp/test_arena_store_unused.json"),
                bot_sandbox: BotSandbox::new_from_env(),
                wasm_dir: PathBuf::from("/tmp/test_arena_wasm"),
                wasm_max_bytes: DEFAULT_ARENA_WASM_MAX_BYTES,
                persistent_store: RwLock::new(PersistentArenaStore {
                    models: HashMap::from([
                        (
                            "a".to_owned(),
                            ArenaModelRecord {
                                model_id: "a".to_owned(),
                                model_name: "a".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                        (
                            "b".to_owned(),
                            ArenaModelRecord {
                                model_id: "b".to_owned(),
                                model_name: "b".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                    ]),
                    completed_matches: Vec::new(),
                }),
                pending_matches: Mutex::new(VecDeque::new()),
                in_flight_matches: DashMap::new(),
                total_matches_reported: AtomicU64::new(0),
                worker_runs: AtomicU64::new(0),
                worker_executed: AtomicU64::new(0),
                worker_idle: AtomicU64::new(0),
                worker_failures: AtomicU64::new(0),
                worker_last_success_at: AtomicU64::new(0),
                worker_last_failure_at: AtomicU64::new(0),
                worker_last_error: RwLock::new(None),
                worker_total_duration_ms: AtomicU64::new(0),
                worker_total_ticks: AtomicU64::new(0),
                worker_warning_matches: AtomicU64::new(0),
                worker_runtime_fallback_matches: AtomicU64::new(0),
                worker_trap_warnings: AtomicU64::new(0),
                worker_timeout_warnings: AtomicU64::new(0),
                worker_draw_matches: AtomicU64::new(0),
                worker_max_duration_ms: AtomicU64::new(0),
                worker_min_duration_ms: AtomicU64::new(0),
                worker_model_win_distribution: RwLock::new(HashMap::new()),
                replay_sequence: AtomicU64::new(0),
                replay_history_capacity: DEFAULT_ARENA_REPLAY_HISTORY_CAP,
                recent_replays: Mutex::new(VecDeque::new()),
                replay_event_sequence: AtomicU64::new(0),
                replay_event_history_capacity: DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP,
                replay_match_history_capacity: DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP,
                replay_events: Mutex::new(VecDeque::new()),
                replay_match_order: Mutex::new(VecDeque::new()),
                replay_matches: RwLock::new(HashMap::new()),
                replay_event_tx: broadcast::channel(DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP).0,
            }),
        };

        let queued = service
            .queue_match(QueueMatchBody {
                model_a_id: "a".to_owned(),
                model_b_id: "b".to_owned(),
                mode: Some("ctf".to_owned()),
                metadata: None,
            })
            .expect("queue should succeed");
        assert_eq!(queued.queued_count, 1);

        let executed = service
            .execute_next_match(ExecuteNextBody {
                max_ticks: Some(120),
                seed: Some(7),
            })
            .expect("execute should succeed");
        assert_eq!(executed.pending_after, 0);
        assert_eq!(executed.report.model_a.matches_played, 1);
        assert_eq!(executed.report.model_b.matches_played, 1);
        assert!(executed.sandbox.ticks_executed > 0);
        assert!(executed.sandbox.ticks_executed <= 120);
        assert_eq!(executed.sandbox.mode, "ctf");
        assert_eq!(executed.sandbox.objective_label, "captures");

        let replays = service.recent_replays(5);
        assert_eq!(replays.total_replays, 1);
        assert_eq!(replays.replays.len(), 1);
        assert_eq!(replays.replays[0].match_id, executed.report.match_id);

        let recent_events = service.recent_replay_events(128, None);
        assert!(recent_events.total_events >= 3);
        assert_eq!(recent_events.returned_events, recent_events.events.len());
        assert!(recent_events.newest_sequence.is_some());

        let match_events = service
            .replay_events_for_match(&executed.report.match_id, 512, None)
            .expect("match replay events should exist");
        assert_eq!(match_events.match_id, executed.report.match_id);
        assert!(match_events.total_events >= 3);
        assert_eq!(match_events.returned_events, match_events.events.len());
        assert!(match_events
            .events
            .iter()
            .any(|event| event.event_type == "tick"));
        assert!(match_events
            .events
            .iter()
            .any(|event| { event.event_type == "match_end" || event.event_type == "match_draw" }));

        let from_newest = service.replay_events_for_match(
            &executed.report.match_id,
            16,
            recent_events.newest_sequence,
        );
        assert!(from_newest.expect("query should succeed").events.is_empty());
    }

    #[test]
    fn worker_execute_next_returns_none_when_queue_empty() {
        let service = ArenaService::new_from_env();
        let outcome = service
            .worker_execute_next(Some(64), Some(1))
            .expect("worker call should not fail");
        assert!(outcome.is_none());
        let stats = service.worker_stats();
        assert_eq!(stats.runs, 1);
        assert_eq!(stats.idle, 1);
        assert_eq!(stats.executed, 0);
        assert_eq!(stats.avg_match_duration_ms, 0.0);
        assert_eq!(stats.model_win_distribution.len(), 0);
    }

    #[test]
    fn worker_stats_track_extended_metrics() {
        let service = ArenaService {
            inner: Arc::new(ArenaInner {
                store_path: PathBuf::from("/tmp/test_arena_store_unused.json"),
                bot_sandbox: BotSandbox::new_from_env(),
                wasm_dir: PathBuf::from("/tmp/test_arena_wasm"),
                wasm_max_bytes: DEFAULT_ARENA_WASM_MAX_BYTES,
                persistent_store: RwLock::new(PersistentArenaStore {
                    models: HashMap::from([
                        (
                            "a".to_owned(),
                            ArenaModelRecord {
                                model_id: "a".to_owned(),
                                model_name: "a".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                        (
                            "b".to_owned(),
                            ArenaModelRecord {
                                model_id: "b".to_owned(),
                                model_name: "b".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                    ]),
                    completed_matches: Vec::new(),
                }),
                pending_matches: Mutex::new(VecDeque::new()),
                in_flight_matches: DashMap::new(),
                total_matches_reported: AtomicU64::new(0),
                worker_runs: AtomicU64::new(0),
                worker_executed: AtomicU64::new(0),
                worker_idle: AtomicU64::new(0),
                worker_failures: AtomicU64::new(0),
                worker_last_success_at: AtomicU64::new(0),
                worker_last_failure_at: AtomicU64::new(0),
                worker_last_error: RwLock::new(None),
                worker_total_duration_ms: AtomicU64::new(0),
                worker_total_ticks: AtomicU64::new(0),
                worker_warning_matches: AtomicU64::new(0),
                worker_runtime_fallback_matches: AtomicU64::new(0),
                worker_trap_warnings: AtomicU64::new(0),
                worker_timeout_warnings: AtomicU64::new(0),
                worker_draw_matches: AtomicU64::new(0),
                worker_max_duration_ms: AtomicU64::new(0),
                worker_min_duration_ms: AtomicU64::new(0),
                worker_model_win_distribution: RwLock::new(HashMap::new()),
                replay_sequence: AtomicU64::new(0),
                replay_history_capacity: DEFAULT_ARENA_REPLAY_HISTORY_CAP,
                recent_replays: Mutex::new(VecDeque::new()),
                replay_event_sequence: AtomicU64::new(0),
                replay_event_history_capacity: DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP,
                replay_match_history_capacity: DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP,
                replay_events: Mutex::new(VecDeque::new()),
                replay_match_order: Mutex::new(VecDeque::new()),
                replay_matches: RwLock::new(HashMap::new()),
                replay_event_tx: broadcast::channel(DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP).0,
            }),
        };

        service
            .queue_match(QueueMatchBody {
                model_a_id: "a".to_owned(),
                model_b_id: "b".to_owned(),
                mode: Some("tdm".to_owned()),
                metadata: None,
            })
            .expect("queue should succeed");
        let outcome = service
            .worker_execute_next(Some(120), Some(42))
            .expect("worker execute should succeed")
            .expect("match should execute");

        let stats = service.worker_stats();
        assert_eq!(stats.runs, 1);
        assert_eq!(stats.executed, 1);
        assert!(stats.total_match_duration_ms >= outcome.sandbox.duration_ms);
        assert!(stats.avg_ticks_executed > 0.0);
        assert!(stats.max_match_duration_ms >= stats.min_match_duration_ms.unwrap_or(0));
        if let Some(winner) = outcome.sandbox.winner_model_id {
            assert_eq!(
                stats
                    .model_win_distribution
                    .get(&winner)
                    .copied()
                    .unwrap_or(0),
                1
            );
        } else {
            assert_eq!(stats.draw_matches, 1);
        }
    }

    #[test]
    fn upload_wasm_rejects_invalid_base64() {
        let service = ArenaService {
            inner: Arc::new(ArenaInner {
                store_path: PathBuf::from("/tmp/test_arena_store_unused.json"),
                bot_sandbox: BotSandbox::new_from_env(),
                wasm_dir: PathBuf::from("/tmp/test_arena_wasm"),
                wasm_max_bytes: DEFAULT_ARENA_WASM_MAX_BYTES,
                persistent_store: RwLock::new(PersistentArenaStore {
                    models: HashMap::from([(
                        "model_x".to_owned(),
                        ArenaModelRecord {
                            model_id: "model_x".to_owned(),
                            model_name: "model_x".to_owned(),
                            provider: "x".to_owned(),
                            version: "1".to_owned(),
                            active: true,
                            created_at: 1,
                            updated_at: 1,
                            last_seen_at: 1,
                            elo_rating: 1000.0,
                            matches_played: 0,
                            wins: 0,
                            losses: 0,
                            draws: 0,
                            cumulative_score: 0,
                        },
                    )]),
                    completed_matches: Vec::new(),
                }),
                pending_matches: Mutex::new(VecDeque::new()),
                in_flight_matches: DashMap::new(),
                total_matches_reported: AtomicU64::new(0),
                worker_runs: AtomicU64::new(0),
                worker_executed: AtomicU64::new(0),
                worker_idle: AtomicU64::new(0),
                worker_failures: AtomicU64::new(0),
                worker_last_success_at: AtomicU64::new(0),
                worker_last_failure_at: AtomicU64::new(0),
                worker_last_error: RwLock::new(None),
                worker_total_duration_ms: AtomicU64::new(0),
                worker_total_ticks: AtomicU64::new(0),
                worker_warning_matches: AtomicU64::new(0),
                worker_runtime_fallback_matches: AtomicU64::new(0),
                worker_trap_warnings: AtomicU64::new(0),
                worker_timeout_warnings: AtomicU64::new(0),
                worker_draw_matches: AtomicU64::new(0),
                worker_max_duration_ms: AtomicU64::new(0),
                worker_min_duration_ms: AtomicU64::new(0),
                worker_model_win_distribution: RwLock::new(HashMap::new()),
                replay_sequence: AtomicU64::new(0),
                replay_history_capacity: DEFAULT_ARENA_REPLAY_HISTORY_CAP,
                recent_replays: Mutex::new(VecDeque::new()),
                replay_event_sequence: AtomicU64::new(0),
                replay_event_history_capacity: DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP,
                replay_match_history_capacity: DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP,
                replay_events: Mutex::new(VecDeque::new()),
                replay_match_order: Mutex::new(VecDeque::new()),
                replay_matches: RwLock::new(HashMap::new()),
                replay_event_tx: broadcast::channel(DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP).0,
            }),
        };

        let result = service.upload_model_wasm(UploadModelWasmBody {
            model_id: "model_x".to_owned(),
            wasm_base64: "!!!not-base64!!!".to_owned(),
            overwrite: Some(true),
        });
        assert!(result.is_err());
    }

    #[test]
    fn simulate_team_battle_runs_10v10() {
        let service = ArenaService {
            inner: Arc::new(ArenaInner {
                store_path: PathBuf::from("/tmp/test_arena_store_unused.json"),
                bot_sandbox: BotSandbox::new_from_env(),
                wasm_dir: PathBuf::from("/tmp/test_arena_wasm"),
                wasm_max_bytes: DEFAULT_ARENA_WASM_MAX_BYTES,
                persistent_store: RwLock::new(PersistentArenaStore {
                    models: HashMap::from([
                        (
                            "a".to_owned(),
                            ArenaModelRecord {
                                model_id: "a".to_owned(),
                                model_name: "a".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                        (
                            "b".to_owned(),
                            ArenaModelRecord {
                                model_id: "b".to_owned(),
                                model_name: "b".to_owned(),
                                provider: "x".to_owned(),
                                version: "1".to_owned(),
                                active: true,
                                created_at: 1,
                                updated_at: 1,
                                last_seen_at: 1,
                                elo_rating: 1000.0,
                                matches_played: 0,
                                wins: 0,
                                losses: 0,
                                draws: 0,
                                cumulative_score: 0,
                            },
                        ),
                    ]),
                    completed_matches: Vec::new(),
                }),
                pending_matches: Mutex::new(VecDeque::new()),
                in_flight_matches: DashMap::new(),
                total_matches_reported: AtomicU64::new(0),
                worker_runs: AtomicU64::new(0),
                worker_executed: AtomicU64::new(0),
                worker_idle: AtomicU64::new(0),
                worker_failures: AtomicU64::new(0),
                worker_last_success_at: AtomicU64::new(0),
                worker_last_failure_at: AtomicU64::new(0),
                worker_last_error: RwLock::new(None),
                worker_total_duration_ms: AtomicU64::new(0),
                worker_total_ticks: AtomicU64::new(0),
                worker_warning_matches: AtomicU64::new(0),
                worker_runtime_fallback_matches: AtomicU64::new(0),
                worker_trap_warnings: AtomicU64::new(0),
                worker_timeout_warnings: AtomicU64::new(0),
                worker_draw_matches: AtomicU64::new(0),
                worker_max_duration_ms: AtomicU64::new(0),
                worker_min_duration_ms: AtomicU64::new(0),
                worker_model_win_distribution: RwLock::new(HashMap::new()),
                replay_sequence: AtomicU64::new(0),
                replay_history_capacity: DEFAULT_ARENA_REPLAY_HISTORY_CAP,
                recent_replays: Mutex::new(VecDeque::new()),
                replay_event_sequence: AtomicU64::new(0),
                replay_event_history_capacity: DEFAULT_ARENA_REPLAY_EVENT_HISTORY_CAP,
                replay_match_history_capacity: DEFAULT_ARENA_REPLAY_MATCH_HISTORY_CAP,
                replay_events: Mutex::new(VecDeque::new()),
                replay_match_order: Mutex::new(VecDeque::new()),
                replay_matches: RwLock::new(HashMap::new()),
                replay_event_tx: broadcast::channel(DEFAULT_ARENA_REPLAY_STREAM_CHANNEL_CAP).0,
            }),
        };

        let result = service
            .simulate_team_battle(SimulateTeamBattleBody {
                model_a_id: "a".to_owned(),
                model_b_id: "b".to_owned(),
                mode: Some("tdm".to_owned()),
                team_size: Some(10),
                rounds: Some(2),
                max_ticks: Some(120),
                seed: Some(11),
            })
            .expect("team simulation should succeed");
        assert_eq!(result.simulation.team_size, 10);
        assert_eq!(result.simulation.rounds, 2);
        assert_eq!(result.simulation.total_engagements, 20);
        assert_eq!(result.simulation.mode, "tdm");
        assert_eq!(result.simulation.rounds_detail.len(), 2);
    }
}
