//! Integration tests for `mcptest workbench` (WOR-1429).
//!
//! The offline path is deterministic: it reads artifacts and writes one
//! self-contained HTML page with no network. The live path is gated behind
//! explicit `--allow-stdio` consent, which the arg parser enforces.

use std::io::Write;

use assert_cmd::Command;
use predicates::prelude::*;

fn mcptest() -> Command {
    Command::cargo_bin("mcptest").expect("binary builds")
}

fn write(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
    let path = dir.join(name);
    let mut f = std::fs::File::create(&path).unwrap();
    f.write_all(body.as_bytes()).unwrap();
    path
}

#[test]
fn builds_a_self_contained_workbench_from_artifacts() {
    let dir = tempfile::tempdir().unwrap();
    let snapshot = write(
        dir.path(),
        "snap.json",
        r#"{"tools":[{"name":"get_weather","description":"weather"}],"resources":[],"prompts":[]}"#,
    );
    let report = write(
        dir.path(),
        "report.json",
        r#"{"summary":{"total":2,"passed":1,"failed":1,"skipped":0},"tests":[{"name":"t1","status":"passed"}]}"#,
    );
    let out = dir.path().join("wb.html");
    mcptest()
        .args(["workbench", "--snapshot"])
        .arg(&snapshot)
        .arg("--report")
        .arg(&report)
        .arg("--out")
        .arg(&out)
        .assert()
        .success();

    let html = std::fs::read_to_string(&out).unwrap();
    assert!(html.starts_with("<!DOCTYPE html>"));
    assert!(html.contains("get_weather"));
    assert!(html.contains("Run results"));
    // Self-contained: no network resource is referenced.
    assert!(!html.contains("http://") && !html.contains("https://"));
}

#[test]
fn live_target_requires_explicit_consent() {
    // --target without --allow-stdio is a clap usage error: it never launches
    // a process without consent.
    mcptest()
        .args(["workbench", "--target", "some-server --flag"])
        .assert()
        .code(2);
}

#[test]
fn no_artifacts_and_no_target_is_a_usage_error() {
    mcptest()
        .args(["workbench"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("at least one artifact"));
}
