//! Completion handler — completion/complete

use serde_json::Value;

use crate::protocol::errors::McpError;
use crate::protocol::types::JsonRpcResponse;
use crate::server::core::Server;
use crate::server::handler::{
    RequestContext, error_response, require_initialization, success_response,
};

impl Server {
    /// Handle completion/complete request
    ///
    /// Provides argument value completion suggestions for prompts and resources.
    pub(crate) async fn handle_completion_complete(&self, ctx: RequestContext) -> JsonRpcResponse {
        if let Err(err) = require_initialization(&ctx) {
            return error_response(ctx.request.id, err.to_jsonrpc());
        }

        // Check if server has completion capability
        let caps = self.capabilities.load();
        if caps.completion.is_none() {
            return error_response(
                ctx.request.id,
                McpError::not_implemented("Completion capability not enabled").to_jsonrpc(),
            );
        }

        // Parse completion request
        let params = ctx.params().cloned().unwrap_or(Value::Null);
        let request: crate::protocol::types::CompleteRequest = match serde_json::from_value(params)
        {
            Ok(req) => req,
            Err(e) => {
                return error_response(
                    ctx.request.id,
                    McpError::validation(
                        "invalid_params",
                        format!("Invalid completion request: {}", e),
                    )
                    .to_jsonrpc(),
                );
            }
        };

        // Execute completion
        match self.completion_manager.complete(request).await {
            Ok(result) => success_response(
                ctx.request.id,
                serde_json::to_value(result).expect("Failed to serialize completion result"),
            ),
            Err(e) => error_response(
                ctx.request.id,
                McpError::internal("completion_failed", e.to_string()).to_jsonrpc(),
            ),
        }
    }
}
