#![allow(clippy::expect_used, clippy::unwrap_used)]

use capo_agent::mcp::config::{load_config, McpServerConfig};
use std::fs;
use tempfile::tempdir;

#[test]
fn loads_global_and_project_with_env_substitution() {
    let agent = tempdir().unwrap();
    let cwd = tempdir().unwrap();

    fs::write(
        agent.path().join("mcp.toml"),
        r#"
[servers.gh]
transport = "stdio"
command = "github-mcp-server"
env = { TOK = "${GH_TOK}" }
"#,
    )
    .unwrap();

    fs::create_dir_all(cwd.path().join(".capo")).unwrap();
    fs::write(
        cwd.path().join(".capo").join("mcp.toml"),
        r#"
[servers.local]
transport = "stdio"
command = "local-mcp"
"#,
    )
    .unwrap();

    let lookup = |k: &str| {
        if k == "GH_TOK" {
            Some("abc123".into())
        } else {
            None
        }
    };
    let (cfg, diags) = load_config(cwd.path(), agent.path(), &lookup).unwrap();
    assert!(diags.is_empty());
    assert!(cfg.servers.contains_key("gh"));
    assert!(cfg.servers.contains_key("local"));
    if let McpServerConfig::Stdio { env, .. } = cfg.servers.get("gh").unwrap() {
        assert_eq!(env.get("TOK").map(String::as_str), Some("abc123"));
    }
}

#[test]
fn missing_files_returns_empty_config() {
    let agent = tempdir().unwrap();
    let cwd = tempdir().unwrap();
    let (cfg, diags) = load_config(cwd.path(), agent.path(), &|_| None).unwrap();
    assert!(cfg.servers.is_empty());
    assert!(diags.is_empty());
}

#[test]
fn project_can_toggle_global_server_with_enabled_only() {
    let agent = tempdir().unwrap();
    let cwd = tempdir().unwrap();
    fs::write(
        agent.path().join("mcp.toml"),
        r#"
[servers.s]
transport = "stdio"
command = "global"
"#,
    )
    .unwrap();
    fs::create_dir_all(cwd.path().join(".capo")).unwrap();
    fs::write(
        cwd.path().join(".capo").join("mcp.toml"),
        r#"
[servers.s]
enabled = false
"#,
    )
    .unwrap();

    let (cfg, diags) = load_config(cwd.path(), agent.path(), &|_| None).unwrap();
    assert!(diags.is_empty());
    match cfg.servers.get("s").unwrap() {
        McpServerConfig::Stdio {
            command, enabled, ..
        } => {
            assert_eq!(command, "global");
            assert!(!*enabled);
        }
        other => panic!("expected stdio, got {other:?}"),
    }
}

#[test]
fn project_command_override_rejected() {
    let agent = tempdir().unwrap();
    let cwd = tempdir().unwrap();
    fs::write(
        agent.path().join("mcp.toml"),
        r#"
[servers.s]
transport = "stdio"
command = "global"
"#,
    )
    .unwrap();
    fs::create_dir_all(cwd.path().join(".capo")).unwrap();
    fs::write(
        cwd.path().join(".capo").join("mcp.toml"),
        r#"
[servers.s]
transport = "stdio"
command = "PROJECT_OVERRIDE"
"#,
    )
    .unwrap();
    let err = load_config(cwd.path(), agent.path(), &|_| None).unwrap_err();
    assert!(err.contains("command"), "{err}");
}
