#![allow(dead_code)]
//! Simulator control commands

use crate::dev::{DevState, SimulatorConfig, SimulatorEnvironment};
use anyhow::Result;
use dialoguer::Select;

/// Start simulator with environment selection
pub async fn start_simulator(state: &mut DevState) -> Result<()> {
    println!("\n╭─────────────────────────────────────────╮");
    println!("│  Start Simulator                         │");
    println!("╰─────────────────────────────────────────╯\n");

    if state.simulator_running {
        println!("  ⚠ Simulator is already running");
        return Ok(());
    }

    let environments = SimulatorEnvironment::all();
    let env_names: Vec<&str> = environments.iter().map(|e| e.name()).collect();

    let selection = Select::new()
        .with_prompt("Select environment")
        .items(&env_names)
        .default(0)
        .interact()?;

    let selected_env = environments[selection];
    let config = SimulatorConfig::default();

    println!("  Starting Godot simulator...");
    println!("  Environment: {}", selected_env.name());
    println!("  Scene: {}", selected_env.scene_path());
    println!("  Project: {}", config.project_path.display());

    match config.launch(selected_env) {
        Ok(child) => {
            let pid = child.id();
            state.process_tracker.add("godot-simulator".to_string(), child);

            // Wait to check if it started successfully
            std::thread::sleep(std::time::Duration::from_millis(500));

            let status_map = state.process_tracker.get_status_map();
            if let Some(status) = status_map.get("godot-simulator") {
                if status.contains("exited") {
                    println!("  ✗ Godot exited immediately");
                    state.simulator_running = false;
                    return Ok(());
                }
            }

            println!("  ✓ Simulator launched successfully (PID: {})", pid);
            state.simulator_running = true;
        }
        Err(e) => {
            println!("  ✗ Failed to start simulator: {}", e);
        }
    }

    Ok(())
}
