//! Integration test for the performance lane of `mcptest run` (WOR-1487).
//!
//! A suite that declares a `performance:` block gets an advisory p95-latency
//! budget folded into the run: the lane reads the run's per-test durations and
//! reports a `performance/p95 ...` row. The budget is advisory, so even an
//! over-budget p95 never fails the run; this test exercises the deterministic
//! within-budget path offline (mock latencies are tiny, well under a 60s
//! budget), so the row appears and the run still exits 0. The over-budget
//! advisory row is covered by the unit tests in `run_live_lanes`. Offline and
//! key-free: the server is an `mcptest mock`.

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

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

/// Absolute path to the built `mcptest` binary, used as the mock server command.
fn mcptest_bin() -> &'static str {
    env!("CARGO_BIN_EXE_mcptest")
}

/// Write a mock manifest exposing one `echo` tool so the ride-along tool test
/// produces a timed result for the p95 budget to read.
fn write_manifest(dir: &std::path::Path) -> std::path::PathBuf {
    let manifest = r#"mock_server:
  name: echo
  tools:
    - name: echo
      description: "Echo a fixed line."
      input_schema:
        type: object
      response:
        isError: false
        content:
          - type: text
            text: "hello"
"#;
    let path = dir.join("echo.yaml");
    std::fs::write(&path, manifest).expect("write mock manifest");
    path
}

/// The mock's one tool test runs in a few milliseconds, well under the 60s p95
/// budget, so the performance lane reports a within-budget (passing) row and the
/// run exits 0. `default_timeout_ms` is declared too, to confirm it parses and
/// wires without breaking the run.
#[test]
fn a_within_budget_performance_block_reports_an_advisory_row_and_passes() {
    let dir = tempfile::tempdir().unwrap();
    let manifest = write_manifest(dir.path());
    let suite = format!(
        r#"servers:
  mock:
    command: ['{bin}', 'mock', '--tools-from', '{manifest}']
tools:
  - name: echo round-trips
    server: mock
    tool: echo
    expect:
      - target: result.content[0].text
        matcher: {{ exact: "hello" }}
performance:
  default_timeout_ms: 30000
  p95_latency_ms: 60000
"#,
        bin = mcptest_bin(),
        manifest = manifest.display(),
    );
    let path = dir.path().join("suite.yml");
    std::fs::write(&path, suite).expect("write suite");
    mcptest()
        .args(["run", "--config", path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicate::str::contains("performance/p95"))
        .stdout(predicate::str::contains("within budget"));
}
