/// Native implementation: probe runtimes via C FFI (popen).

#cfg(target="native")

fn runtime_name(kind : RuntimeType) -> String {
  match kind {
    Wasmtime => "wasmtime"
    Wasmer => "wasmer"
    Wazero => "wazero"
    Node => "node"
    Bun => "bun"
    Deno => "deno"
  }
}

#cfg(target="native")
fn runtime_version_flag(kind : RuntimeType) -> String {
  match kind {
    Wasmtime => "--version"
    Wasmer => "--version"
    Wazero => "version"
    Node => "--version"
    Bun => "--version"
    Deno => "--version"
  }
}

/// Probe a single runtime.
#cfg(target="native")
fn probe_runtime(kind : RuntimeType) -> RuntimeProbe {
  let name = runtime_name(kind)
  let version_flag = runtime_version_flag(kind)
  let cmd = "which " + name + " 2>/dev/null"
  let path = popen(cmd)
  match path {
    Some(path) => {
      let version_cmd = name + " " + version_flag + " 2>/dev/null"
      let version = popen(version_cmd)
      {
        name,
        kind,
        installed: true,
        version,
        path: Some(path),
      }
    }
    None => {
      { name, kind, installed: false, version: None, path: None }
    }
  }
}

/// Probe all supported WASM runtimes.
#cfg(target="native")
pub fn probe_all() -> WASMEnvReport {
  let moon_version = match popen("moon --version 2>/dev/null") {
    Some(v) => v
    None => "unknown"
  }

  let runtimes = [
    probe_runtime(Wasmtime),
    probe_runtime(Wasmer),
    probe_runtime(Wazero),
    probe_runtime(Node),
    probe_runtime(Bun),
    probe_runtime(Deno),
  ]

  { moon_version, runtimes }
}

#cfg(target="native")
#borrow(cmd)
extern "c" fn popen(cmd : String) -> Option[String] = "moonwasm_probe_ffi_popen"