//! Handler for `mcptest inspect`.

use anyhow::{anyhow, Result};

use crate::cli::args::InspectCliArgs;
use crate::commands::{self, InspectTarget};

/// Map the CLI args to a [`commands::InspectArgs`] and run the REPL. Requires
/// exactly one target: `--url` for streamable HTTP, or a trailing command for
/// stdio.
pub(crate) fn inspect_command(args: InspectCliArgs) -> Result<i32> {
    let target = match (args.url, args.command.is_empty()) {
        (Some(_), false) => {
            return Err(anyhow!("pass either --url or a stdio command, not both"));
        }
        (None, true) => {
            return Err(anyhow!(
                "inspect needs a target: --url <URL>, or a stdio command after `--`"
            ));
        }
        (Some(url), true) => {
            let bearer_token = args
                .bearer_token_env
                .as_ref()
                .and_then(|name| std::env::var(name).ok());
            InspectTarget::Url { url, bearer_token }
        }
        (None, false) => {
            let mut it = args.command.into_iter();
            let command = it.next().expect("command is non-empty");
            InspectTarget::Stdio {
                command,
                args: it.collect(),
            }
        }
    };
    commands::run_inspect(commands::InspectArgs { target })
}
