// Process-level coverage for relay control CLI argument handling.
//
// Scope: launch the real `lesavka-relayctl` binary for argument-only paths.
// Targets: `client/src/bin/lesavka-relayctl.rs`.
// Why: CLI-only failures should stay fast and local instead of retrying a bad
// network endpoint.

use serial_test::serial;
use std::path::{Path, PathBuf};
use std::process::Command;

fn candidate_dirs() -> Vec<PathBuf> {
    let exe = std::env::current_exe().expect("current exe path");
    let mut dirs = Vec::new();
    if let Some(parent) = exe.parent() {
        dirs.push(parent.to_path_buf());
        if let Some(grand) = parent.parent() {
            dirs.push(grand.to_path_buf());
        }
    }
    dirs.push(PathBuf::from("target/debug"));
    dirs.push(PathBuf::from("target/llvm-cov-target/debug"));
    dirs
}

fn find_binary(name: &str) -> Option<PathBuf> {
    candidate_dirs()
        .into_iter()
        .map(|dir| dir.join(name))
        .find(|path| path.exists() && path.is_file())
}

#[test]
#[serial]
fn relayctl_help_exits_successfully() {
    let Some(bin) = find_binary("lesavka-relayctl") else {
        return;
    };

    let output = Command::new(Path::new(&bin))
        .arg("--help")
        .output()
        .expect("spawn lesavka-relayctl --help");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("lesavka-relayctl"));
}

#[test]
#[serial]
fn relayctl_rejects_bad_arguments_before_network_use() {
    let Some(bin) = find_binary("lesavka-relayctl") else {
        return;
    };

    let output = Command::new(Path::new(&bin))
        .arg("nonsense")
        .output()
        .expect("spawn lesavka-relayctl bad command");

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("unknown command"));
}
