///|
/// What runs this build of the command.
priv enum Build {
  /// The full path of this program.
  Native(String)
  /// The full path of the wasm file, when there is one.
  Wasm(String?)
}

///|
/// The programs on the `PATH` that can run a wasm file, as full paths.
priv struct WasmRuntimes {
  moonrun : String?
  moonx : String?
}

///|
/// The package that `moonx` runs: the same version of this command.
fn package_reference(version : @contracts.Version) -> String {
  "moonrockz/mission-control-cli@\{version.to_string()}"
}

///|
/// The arguments that run the server of an instance. They have the port, because the
/// environment of the server can have another default.
fn serve_args(
  name : @app.InstanceName,
  choice : @core.PortChoice,
) -> Array[String] {
  let port = match choice {
    Fixed(port) | Preferred(port) => port.to_int()
    Free => 0
  }
  ["serve", "--instance", name.to_string(), "--port", port.to_string()]
}

///|
/// The program that runs the server in the background. A native build runs itself. A
/// wasm build runs its file with `moonrun`, or else its package with `moonx`. `None`
/// says that no program can run it.
fn starter_of(
  build : Build,
  runtimes : WasmRuntimes,
  args : Array[String],
) -> @server.Starter? {
  match (build, runtimes) {
    (Native(program), _) =>
      Some({ program, args: ReadOnlyArray::from_array(args), })
    (Wasm(Some(file)), { moonrun: Some(program), .. }) =>
      // `moonrun` gives the program each argument after `--`.
      Some({ program, args: ReadOnlyArray::from_array([file, "--", ..args]), })
    (Wasm(_), { moonx: Some(program), .. }) =>
      Some({
        program,
        args: ReadOnlyArray::from_array(
          [package_reference(@contracts.version()), ..args],
        ),
      })
    (Wasm(_), _) => None
  }
}

///|
/// The value of a variable on Windows, which ignores the case of its name.
fn windows_variable(env_vars : Map[String, String], name : String) -> String? {
  env_vars
  .iter()
  .find_first(entry => entry.0.to_upper() == name.to_upper())
  .map(entry => entry.1)
}

///|
/// The folders of the `PATH`. On Windows the name of the variable can be `Path`.
fn path_folders(
  env_vars : Map[String, String],
  platform : @core.Platform,
) -> Array[String] {
  let (value, separator) = match platform {
    Windows => (windows_variable(env_vars, "PATH"), ";")
    MacOs | Linux => (env_vars.get("PATH"), ":")
  }
  // A folder that is not absolute is for the working directory of another program.
  value
  .unwrap_or("")
  .split(separator)
  .filter_map(text => {
    Some(@core.FolderPath::FolderPath(text.to_owned(), platform).to_string()) catch {
      _ => None
    }
  })
  .collect()
}

///|
/// The full path of a program on the `PATH`. Windows can start a `.exe` file only.
///
/// This program gives a full path to the system each time it starts a program. For a
/// name, Windows looks in the working directory before it looks in the `PATH`, and the
/// working directory can be a repository of another person.
async fn find_program(
  name : String,
  folders : Array[String],
  platform : @core.Platform,
) -> String? noraise {
  for folder in folders {
    let path = match platform {
      Windows if name.to_lower().has_suffix(".exe") => "\{folder}\\\{name}"
      Windows => "\{folder}\\\{name}.exe"
      MacOs | Linux => "\{folder}/\{name}"
    }
    if is_program(path, platform) {
      return Some(path)
    }
  }
  None
}

///|
/// True for a file that the system can start.
async fn is_program(path : String, platform : @core.Platform) -> Bool noraise {
  (@fs.kind(path) catch { _ => return false }) is Regular &&
  (platform is Windows || (@fs.can_execute(path) catch { _ => false }))
}

///|
/// What this process runs. The server has another working directory, so a relative path
/// is not sufficient.
async fn this_build() -> Build noraise {
  guard program_path() is Some(path) else { return Wasm(None) }
  let full = Some(@fs.realpath(path)) catch { _ => None }
  if is_native {
    Native(full.unwrap_or(path))
  } else {
    Wasm(full)
  }
}

///|
#cfg(target="native")
let is_native : Bool = true

///|
#cfg(target="wasm")
let is_native : Bool = false

///|
/// The wasm file, as the runtime got it.
#cfg(target="wasm")
fn program_path() -> String? {
  @env.args().get(0)
}

///|
/// The system knows the path of the program. The first argument can have only its name.
#cfg(all(target="native", platform="windows"))
fn program_path() -> String? {
  Some(current_program())
}

///|
#cfg(all(target="native", platform="windows"))
extern "C" fn current_program() -> String = "moonbit_rt_get_current_exe"

///|
/// The system knows the path of the program. The first argument can have only its name.
#cfg(all(target="native", not(platform="windows")))
fn program_path() -> String? {
  Some(@utf8.decode_lossy(current_program()))
}

///|
#cfg(all(target="native", not(platform="windows")))
extern "C" fn current_program() -> Bytes = "moonbit_rt_get_current_exe"