//! Debug: try several timeout variants to see which actually
//! short-circuit. NOT a polished example — just diagnosis.
//!
//! Run with `SUPERMACHINE_TIMEOUT_TRACE=1` to see watchdog fires.

use std::time::Duration;

use supermachine::{Image, VmConfig};

fn variant(vm: &supermachine::Vm, label: &str, argv: &[&str]) {
    let argv_owned: Vec<String> = argv.iter().map(|s| s.to_string()).collect();
    let out = vm
        .exec_builder()
        .argv(argv_owned)
        .timeout(Duration::from_millis(500))
        .output();
    match out {
        Ok(o) => println!(
            "  {label:30} timed_out={} duration={:?} status={:?}",
            o.timed_out,
            o.duration,
            o.status.code()
        ),
        Err(e) => println!("  {label:30} ERR {e}"),
    }
}

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

    println!("=== timeout 500ms variants ===");
    // 1. Direct sleep — agent's pid_for_signal IS sleep's pid.
    variant(&vm, "sleep direct", &["sleep", "10"]);
    // 2. sh -c "sleep" — pid is sh, sh's child is sleep.
    variant(&vm, "sh -c sleep", &["sh", "-c", "sleep 10"]);
    // 3. sh -c sleep + post-print — same shape but provokes
    //    completion-after-kill.
    variant(
        &vm,
        "sh -c sleep+echo",
        &["sh", "-c", "sleep 10; echo never"],
    );
    // 4. Busy loop — no syscall to interrupt.
    variant(
        &vm,
        "busy loop",
        &[
            "sh",
            "-c",
            "i=0; while [ $i -lt 1000000000 ]; do i=$((i+1)); done; echo done",
        ],
    );
    // 5. tight read — should be SIGKILL'able.
    variant(
        &vm,
        "cat /dev/zero >/dev/null",
        &["sh", "-c", "cat /dev/zero > /dev/null"],
    );

    vm.stop()?;
    Ok(())
}
