//! Système Bevy (Update) qui traite les commandes reçues de l'éditeur.
//!
//! Play / Pause / Stop sont traités directement.
//! GetEntities pose un flag [`PendingGetEntities`] consommé par le système
//! exclusif [`send_entity_list`](crate::entities::send_entity_list) dans Last.

use bevy::prelude::*;
use san_motor::debug_protocol::{EditorToGame, GamePlayState, GameToEditor};

use crate::{CameraFollowLive, PendingEntityProps, PendingScreenshot, entities::PendingGetEntities, DebugChannel};

/// Lit les commandes reçues de l'éditeur depuis le canal WebSocket.
pub fn handle_debug_messages(
    channel: Res<DebugChannel>,
    mut pending: ResMut<PendingGetEntities>,
    mut cam_follow: ResMut<CameraFollowLive>,
    mut entity_props: ResMut<PendingEntityProps>,
    mut screenshot: ResMut<PendingScreenshot>,
) {
    while let Ok(cmd) = channel.rx.lock().unwrap().try_recv() {
        match cmd {
            EditorToGame::Play => {
                info!("[san-debug] ▶ Play reçu");
                let _ = channel
                    .tx
                    .send(GameToEditor::StateChanged { state: GamePlayState::Playing });
            }
            EditorToGame::Pause => {
                info!("[san-debug] ⏸ Pause reçu");
                let _ = channel
                    .tx
                    .send(GameToEditor::StateChanged { state: GamePlayState::Paused });
            }
            EditorToGame::Stop => {
                info!("[san-debug] ⏹ Stop reçu");
                let _ = channel
                    .tx
                    .send(GameToEditor::StateChanged { state: GamePlayState::Stopped });
            }
            EditorToGame::GetEntities => {
                pending.0 = true;
            }
            EditorToGame::SetCameraFollow { offset, smooth, look_at_target } => {
                info!("[san-debug] 📷 SetCameraFollow offset={offset:?} smooth={smooth}");
                cam_follow.offset = Some(offset);
                cam_follow.smooth = Some(smooth);
                cam_follow.look_at_target = Some(look_at_target);
            }
            EditorToGame::SetEntityProperties { entity_name, props } => {
                entity_props.0.push((entity_name, props));
            }
            EditorToGame::TakeScreenshot => {
                info!("[san-debug] 📸 TakeScreenshot reçu");
                screenshot.0 = true;
            }
        }
    }
}
