//! Handler for `mcptest exec --connection-server`.

use anyhow::Result;

use crate::cli::args::ExecArgs;
use crate::cli::GlobalArgs;
use crate::commands;

/// Handle `mcptest exec --connection-server`. Builds a Tokio runtime,
/// resolves the configured MCP server command, and hands off to
/// [`commands::run_exec`].
pub(crate) fn exec_command(global: &GlobalArgs, args: ExecArgs) -> Result<i32> {
    let server_command = resolve_exec_server_command(global)?;
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    rt.block_on(commands::run_exec(commands::ExecRunArgs {
        connection_server: args.connection_server,
        config: args.config.or_else(|| global.config.clone()),
        debug_output: args.debug_output,
        verbose: args.verbose || global.verbose,
        ipc_version: args.ipc_version,
        no_cache: args.no_cache,
        no_cassette: args.no_cassette,
        record_cassettes: args.record_cassettes,
        server_command,
    }))
}

/// Pull the MCP server command for exec mode out of the global flags.
///
/// Priority: `--server-command` (shell-split), then `--server-url`
/// rendered as a one-arg URL probe (rejected for v1.1 because exec
/// mode is stdio-only). Returns an empty vec when neither is set so
/// the backend can fail with a clear message.
fn resolve_exec_server_command(global: &GlobalArgs) -> Result<Vec<String>> {
    if let Some(cmd) = &global.server_command {
        let parts = shell_words::split(cmd)
            .map_err(|e| anyhow::anyhow!("could not parse --server-command: {e}"))?;
        return Ok(parts);
    }
    if global.server_url.is_some() {
        return Err(anyhow::anyhow!(
            "exec mode only supports stdio servers in v1.1; pass --server-command \"./your-server\""
        ));
    }
    Ok(Vec::new())
}
