use crate::ecs::world::World;
use crate::mcp::McpResponse;

pub(crate) fn mcp_set_script(
    world: &mut World,
    request: crate::mcp::SetScriptRequest,
) -> Result<McpResponse, McpResponse> {
    use crate::ecs::script::components::{Script, ScriptSource};

    let enabled = request.enabled.unwrap_or(true);
    let entity = super::resolve_entity(world, &request.name)?;

    let script = Script {
        source: ScriptSource::Embedded {
            source: request.source,
        },
        enabled,
    };

    world.set_script(entity, script);
    Ok(McpResponse::Success(format!(
        "Script set on '{}'",
        request.name
    )))
}

pub(crate) fn mcp_remove_script(
    world: &mut World,
    request: crate::mcp::RemoveScriptRequest,
) -> Result<McpResponse, McpResponse> {
    let entity = super::resolve_entity(world, &request.name)?;

    world.remove_script(entity);
    Ok(McpResponse::Success(format!(
        "Script removed from '{}'",
        request.name
    )))
}

#[cfg(feature = "scripting")]
pub(crate) fn mcp_set_game_state(
    world: &mut World,
    request: crate::mcp::SetGameStateRequest,
) -> McpResponse {
    for (key, value) in request.values {
        world.resources.script_runtime.game_state.insert(key, value);
    }
    McpResponse::Success("Game state updated".to_string())
}

#[cfg(not(feature = "scripting"))]
pub(crate) fn mcp_set_game_state(
    _world: &mut World,
    _request: crate::mcp::SetGameStateRequest,
) -> McpResponse {
    McpResponse::Error("Scripting feature not enabled".to_string())
}

#[cfg(feature = "scripting")]
pub(crate) fn mcp_get_game_state(
    world: &mut World,
    request: crate::mcp::GetGameStateRequest,
) -> McpResponse {
    let state = match request.keys {
        Some(keys) => {
            let mut result = std::collections::HashMap::new();
            for key in keys {
                if let Some(&value) = world.resources.script_runtime.game_state.get(&key) {
                    result.insert(key, value);
                }
            }
            result
        }
        None => world.resources.script_runtime.game_state.clone(),
    };

    McpResponse::GameState(state)
}

#[cfg(not(feature = "scripting"))]
pub(crate) fn mcp_get_game_state(
    _world: &mut World,
    _request: crate::mcp::GetGameStateRequest,
) -> McpResponse {
    McpResponse::Error("Scripting feature not enabled".to_string())
}
