use std::io::Write;
use std::process::{Command, Stdio};

use assert_cmd::cargo::cargo_bin;

#[test]
fn mcp_stdio_lists_tools() {
    let home = tempfile::tempdir().unwrap();
    let mut child = Command::new(cargo_bin("multi-brain"))
        .arg("--home")
        .arg(home.path())
        .arg("mcp")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("spawn mcp");
    {
        let stdin = child.stdin.as_mut().unwrap();
        writeln!(
            stdin,
            "{}",
            serde_json::json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})
        )
        .unwrap();
    }
    let output = child.wait_with_output().unwrap();
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.contains("list_brains"));
    assert!(stdout.contains("ask_brain"));
    assert!(stdout.contains("brain_events"));
}

#[test]
fn mcp_stdio_can_spawn_ask_inspect_and_stop_mock_harness() {
    let home = tempfile::tempdir().unwrap();
    let cwd = tempfile::tempdir().unwrap();
    let mock = std::env::current_dir()
        .unwrap()
        .join("tests/fixtures/mock-claude");
    let mut child = Command::new(cargo_bin("multi-brain"))
        .arg("--home")
        .arg(home.path())
        .arg("mcp")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("spawn mcp");
    {
        let stdin = child.stdin.as_mut().unwrap();
        let config = serde_json::json!({
            "name": "mcp-reviewer",
            "kind": "claude",
            "command": mock.display().to_string(),
            "args": [],
            "cwd": cwd.path().display().to_string(),
            "personality": "transparent reviewer",
            "env": []
        });
        writeln!(
            stdin,
            "{}",
            serde_json::json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"ensure_brain","arguments":config}})
        )
        .unwrap();
        writeln!(
            stdin,
            "{}",
            serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask_brain","arguments":{"from":"tester","to":"mcp-reviewer","body":"inspect this"}}})
        )
        .unwrap();
        writeln!(
            stdin,
            "{}",
            serde_json::json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"brain_events","arguments":{"name":"mcp-reviewer","max":20}}})
        )
        .unwrap();
        writeln!(
            stdin,
            "{}",
            serde_json::json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"stop_brain","arguments":{"name":"mcp-reviewer"}}})
        )
        .unwrap();
    }
    let output = child.wait_with_output().unwrap();
    let stdout = String::from_utf8(output.stdout).unwrap();
    assert!(stdout.contains("mcp-reviewer"));
    assert!(stdout.contains("inspect this"));
    assert!(stdout.contains("stdin"));
}
