/// WASM runtime type detected on the system.
pub enum RuntimeType {
  Wasmtime
  Wasmer
  Wazero
  Node
  Bun
  Deno
}

/// Result for a single runtime probe.
pub struct RuntimeProbe {
  name : String
  kind : RuntimeType
  installed : Bool
  version : Option[String]
  path : Option[String]
}

/// Overall WASM environment report.
pub struct WASMEnvReport {
  moon_version : String
  runtimes : Array[RuntimeProbe]
}

/// Replace newlines with spaces for compact display.
fn inline(s : String) -> String {
  let sb = StringBuilder()
  for i = 0; i < s.length(); i = i + 1 {
    let ch = s[i]
    if ch == '\n'.to_int().to_uint16() || ch == '\r'.to_int().to_uint16() {
      sb.write_char(' ')
    } else {
      sb.write_char(ch.unsafe_to_char())
    }
  }
  sb.to_string()
}

/// Format the report as a readable string.
pub fn report_to_string(report : WASMEnvReport) -> String {
  let sb = StringBuilder()
  sb.write_string("WASM Runtime Environment Report")
  sb.write_string("\n================================")
  sb.write_string("\nVersion:")
  sb.write_string("\n  MoonBit : ")
  sb.write_string(report.moon_version)
  sb.write_string("\n")
  sb.write_string("\nInstalled WASM Runtimes:")

  let mut found_any = false
  report.runtimes.each(fn(r) {
    if r.installed {
      found_any = true
      sb.write_string("\n  [X] ")
      sb.write_string(r.name)
      match r.version {
        Some(v) => {
          sb.write_string(" (")
          sb.write_string(inline(v))
          sb.write_string(")")
        }
        None => ()
      }
      match r.path {
        Some(p) => {
          sb.write_string(" [")
          sb.write_string(p)
          sb.write_string("]")
        }
        None => ()
      }
    }
  })
  if !found_any {
    sb.write_string("\n  (no WASM runtimes detected on this system)")
  }

  sb.write_string("\n")
  sb.write_string("\nUninstalled Runtimes:")
  report.runtimes.each(fn(r) {
    if !r.installed {
      sb.write_string("\n  [ ] ")
      sb.write_string(r.name)
    }
  })

  sb.to_string()
}