//! Smoke test: stage_file + chain compose with a single RPC.
//! Verifies (1) file is staged, (2) chained argvs run with `&&`
//! semantics, (3) stdout/stderr from each child reach the host.

use std::time::Duration;
use supermachine::{Image, VmConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let snap = format!(
        "{}/.local/supermachine-snapshots/rust_1_slim",
        std::env::var("HOME")?
    );
    let image = Image::from_snapshot(&snap)?;
    let vm = image.acquire_with(&VmConfig::new())?;

    println!("=== test 1: plain exec (regression check) ===");
    let out = vm
        .exec_builder()
        .argv(["echo", "hello"].iter().copied())
        .timeout(Duration::from_secs(10))
        .output()?;
    println!(
        "  stdout: {:?}  status: {}",
        String::from_utf8_lossy(&out.stdout).trim(),
        out.status
    );

    println!("\n=== test 2: stage_file + argv (no shell) ===");
    let out = vm
        .exec_builder()
        .stage_file("/tmp/probe.txt", b"contents-from-stage".to_vec())
        .argv(["cat", "/tmp/probe.txt"].iter().copied())
        .timeout(Duration::from_secs(10))
        .output()?;
    println!(
        "  stdout: {:?}  status: {}",
        String::from_utf8_lossy(&out.stdout).trim(),
        out.status
    );

    println!("\n=== test 3: chain (rustc + run binary) ===");
    let out = vm
        .exec_builder()
        .stage_file(
            "/tmp/main.rs",
            b"fn main(){ println!(\"hi-from-rustc\"); }".to_vec(),
        )
        .argv(
            ["rustc", "-O", "/tmp/main.rs", "-o", "/tmp/m"]
                .iter()
                .copied(),
        )
        .chain(["/tmp/m"].iter().copied())
        .timeout(Duration::from_secs(60))
        .output()?;
    println!(
        "  stdout: {:?}  status: {}",
        String::from_utf8_lossy(&out.stdout).trim(),
        out.status
    );

    println!("\n=== test 4: chain stops on failure ===");
    let out = vm
        .exec_builder()
        .argv(["false"].iter().copied())
        .chain(["echo", "should-not-print"].iter().copied())
        .timeout(Duration::from_secs(10))
        .output()?;
    println!(
        "  stdout: {:?}  status: {}",
        String::from_utf8_lossy(&out.stdout).trim(),
        out.status
    );
    Ok(())
}
