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

pub(crate) fn mcp_play_animation(
    world: &mut World,
    request: crate::mcp::PlayAnimationRequest,
) -> Result<McpResponse, McpResponse> {
    let looping = request.looping.unwrap_or(true);
    let speed = request.speed.unwrap_or(1.0);
    let blend_duration = request.blend_duration.unwrap_or(0.0);
    let entity = super::resolve_entity(world, &request.name)?;

    let Some(player) = world.get_animation_player_mut(entity) else {
        return Err(McpResponse::Error(format!(
            "Entity '{}' has no AnimationPlayer",
            request.name
        )));
    };

    let clip_index = if let Ok(index) = request.clip.parse::<usize>() {
        index
    } else {
        match player.clips.iter().position(|c| c.name == request.clip) {
            Some(index) => index,
            None => {
                return Err(McpResponse::Error(format!(
                    "Animation clip '{}' not found",
                    request.clip
                )));
            }
        }
    };

    player.looping = looping;
    player.speed = speed;

    if blend_duration > 0.0 {
        player.blend_to(clip_index, blend_duration);
    } else {
        player.play(clip_index);
    }

    Ok(McpResponse::Success(format!(
        "Playing animation '{}' on '{}'",
        request.clip, request.name
    )))
}

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

    let Some(player) = world.get_animation_player_mut(entity) else {
        return Err(McpResponse::Error(format!(
            "Entity '{}' has no AnimationPlayer",
            request.name
        )));
    };

    player.stop();
    Ok(McpResponse::Success(format!(
        "Animation stopped on '{}'",
        request.name
    )))
}

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

    let Some(player) = world.get_animation_player(entity) else {
        return Err(McpResponse::Error(format!(
            "Entity '{}' has no AnimationPlayer",
            request.name
        )));
    };

    let names: Vec<String> = player.clips.iter().map(|c| c.name.clone()).collect();
    Ok(McpResponse::AnimationList(names))
}
