//! Demonstrate the public tracing surface.
//!
//! Embedders install a `tracing-subscriber` and the lib emits
//! spans for bake / acquire / snapshot. Any subscriber works;
//! this example uses a plain stderr fmt layer.
//!
//! Run with:
//!   cargo run --release --example _tracing_demo
//!
//! For JSON logs (machine-readable):
//!   RUST_LOG=info cargo run --release --example _tracing_demo

use std::io::Read;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Embedder side: install any tracing-subscriber. The lib
    // doesn't pin a particular subscriber implementation.
    use tracing_subscriber::fmt::format::FmtSpan;
    use tracing_subscriber::EnvFilter;
    tracing_subscriber::fmt()
        .with_target(false)
        .with_span_events(FmtSpan::CLOSE)
        .with_env_filter(
            EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| EnvFilter::new("info,supermachine=info")),
        )
        .init();

    let snap = format!(
        "{}/.local/supermachine-snapshots/rust_1_slim",
        std::env::var("HOME")?
    );
    let image = supermachine::Image::from_snapshot(&snap)?;
    let pool = image.pool().min(1).max(1).build()?;

    let vm = pool.acquire()?;
    let mut child = vm.exec(["sh", "-c", "echo hello-from-traced-exec"])?;
    let mut out = String::new();
    child.stdout().unwrap().read_to_string(&mut out).ok();
    let _ = child.wait();
    eprintln!("[exec output] {}", out.trim());

    Ok(())
}
