//! `aerocontext-mcp` — MCP stdio server for the aerocontext system.
//!
//! Stdout carries the MCP transport, so nothing else may write to it;
//! diagnostics go to stderr through `tracing`, filtered by `RUST_LOG`
//! (default `info` — stderr surfaces in MCP client logs).

// -h/-V results print to stdout (before the transport starts); the
// final failure line goes to stderr for the human reading client logs.
#![allow(clippy::print_stdout, clippy::print_stderr)]

use std::process::ExitCode;

use aerocontext_mcp::error::render_chain;
use tracing_subscriber::EnvFilter;

#[tokio::main]
async fn main() -> ExitCode {
    // Answer -h/-V instead of silently waiting for an MCP handshake on
    // stdin; any other argument is a usage error.
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.as_slice() {
        [] => {}
        [flag] if matches!(flag.as_str(), "-h" | "--help") => {
            println!(concat!(
                "aerocontext-mcp ",
                env!("CARGO_PKG_VERSION"),
                " — MCP stdio server for the aerocontext system\n\n",
                "Run with no arguments under an MCP client; stdout is the transport.\n",
                "Prefer `v99n62 setup` for client configuration."
            ));
            return ExitCode::SUCCESS;
        }
        [flag] if matches!(flag.as_str(), "-V" | "--version") => {
            println!(concat!("aerocontext-mcp ", env!("CARGO_PKG_VERSION")));
            return ExitCode::SUCCESS;
        }
        other => {
            eprintln!("error: unexpected arguments {other:?}; run with no arguments (MCP stdio)");
            return ExitCode::FAILURE;
        }
    }
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .with_ansi(false)
        .init();
    match aerocontext_mcp::serve_stdio().await {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("error: {}", render_chain(&error));
            ExitCode::FAILURE
        }
    }
}
