use std::env;
use std::process::ExitCode;

use brokk_bifrost::lsp::run_lsp_stdio_server;
use brokk_bifrost::mcp_common::McpRenderOptions;
use brokk_bifrost::mcp_core::{run_core_stdio_server, run_searchtools_stdio_server};
use brokk_bifrost::mcp_extended::run_extended_stdio_server;
use brokk_bifrost::mcp_slopcop::run_slopcop_stdio_server;

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("{err}");
            ExitCode::FAILURE
        }
    }
}

fn run() -> Result<(), String> {
    let mut args = env::args().skip(1);
    let mut root =
        env::current_dir().map_err(|err| format!("Failed to get current directory: {err}"))?;
    let mut server_mode = None;
    let mut render_options = McpRenderOptions::default();

    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--root" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--root requires a path".to_string())?;
                root = value.into();
            }
            "--server" => {
                let value = args
                    .next()
                    .ok_or_else(|| "--server requires a mode".to_string())?;
                server_mode = Some(value);
            }
            "--no-line-numbers" => {
                render_options.render_line_numbers = false;
            }
            "--help" | "-h" => {
                print_help();
                return Ok(());
            }
            "--version" | "-V" => {
                println!("bifrost {}", env!("CARGO_PKG_VERSION"));
                return Ok(());
            }
            other => {
                return Err(format!("Unknown argument: {other}"));
            }
        }
    }

    match server_mode.as_deref() {
        Some("searchtools") => run_searchtools_stdio_server(root, render_options),
        Some("core") => run_core_stdio_server(root, render_options),
        Some("extended") => run_extended_stdio_server(root, render_options),
        Some("slopcop") => run_slopcop_stdio_server(root, render_options),
        Some("lsp") => run_lsp_stdio_server(root),
        Some(other) => Err(format!("Unsupported server mode: {other}")),
        None => {
            print_help();
            Err("No mode selected".to_string())
        }
    }
}

fn print_help() {
    println!("Usage: bifrost --root PROJECT_ROOT --server searchtools");
    println!("       bifrost --root PROJECT_ROOT --server searchtools --no-line-numbers");
    println!("       bifrost --root PROJECT_ROOT --server core");
    println!("       bifrost --root PROJECT_ROOT --server extended");
    println!("       bifrost --root PROJECT_ROOT --server slopcop");
    println!("       bifrost --root PROJECT_ROOT --server lsp");
    println!("       bifrost --version");
}
