///|
/// The servers, the browser and the desktop app of this machine.
priv struct MachineLauncher {
  env_vars : Map[String, String]
  platform : @core.Platform
  /// The folder reads of a server that runs in this process. They can need 40 seconds,
  /// so the program does not wait for this group. It ends with `@env.exit`.
  reads : @async.TaskGroup[Unit]
  /// The servers that this process found, by the name of their instance.
  servers : Map[String, @server.RunningServer]
}

///|
/// How long a start has to be silent, in milliseconds.
let late_limit : Int32 = 1000

///|
/// The reason of an error of the system, for people.
fn call_failure(error : @server.ServerCallError) -> @command.LaunchFailure {
  match error {
    Refused(text) => Refused(text)
    NotReachable(text) | BadReply(text) => NotReachable(text)
  }
}

///|
fn start_failure(failure : @core.StartFailure) -> @command.LaunchFailure {
  match failure {
    PortInUse(port) => PortInUse(port)
    BadProjectFile(path~, message~) =>
      NotStarted(reason="\{path} cannot be used. \{message}", log=None)
    Other(reason) => NotStarted(reason~, log=None)
  }
}

///|
fn MachineLauncher::base(
  self : MachineLauncher,
) -> @core.BaseFolder raise @command.LaunchFailure {
  @core.BaseFolder::of_env(self.platform, self.env_vars) catch {
    error => raise NoBaseFolder(error)
  }
}

///|
/// Keeps a server for the next calls, and gives what a command can know about it.
fn MachineLauncher::remember(
  self : MachineLauncher,
  server : @server.RunningServer,
) -> @command.ServerInfo {
  let instance = server.instance()
  self.servers[instance.to_string()] = server
  { instance, version: server.version(), port: server.port(), }
}

///|
/// The server of an instance that `start` or `serve` gave before.
fn MachineLauncher::server_of(
  self : MachineLauncher,
  info : @command.ServerInfo,
) -> @server.RunningServer raise @command.LaunchFailure {
  let name = info.instance.to_string()
  guard self.servers.get(name) is Some(server) else {
    raise NotReachable("No command found the server of the instance \{name}.")
  }
  server
}

///|
/// The program that runs the server in the background, if there is one.
async fn MachineLauncher::starter(
  self : MachineLauncher,
  name : @app.InstanceName,
  choice : @core.PortChoice,
) -> @server.Starter? noraise {
  let build = this_build()
  let runtimes = match build {
    Native(_) => { moonrun: None, moonx: None, }
    Wasm(_) => {
      let folders = path_folders(self.env_vars, self.platform)
      let program = name => find_program(name, folders, self.platform)
      { moonrun: program("moonrun"), moonx: program("moonx"), }
    }
  }
  starter_of(build, runtimes, serve_args(name, choice))
}

///|
fn wait_failure(error : @server.StartError) -> @command.LaunchFailure {
  match error {
    PortInUse(port) => PortInUse(port)
    Failed(reason~, log_tail~, log~) =>
      NotStarted(reason~, log=Some({ path: log, last_lines: log_tail, }))
  }
}

///|
/// Finds or starts a server. Without a program that can run it, a server that runs is
/// still good.
async fn find_or_start(
  folder : @core.InstanceFolder,
  starter : @server.Starter?,
) -> @server.RunningServer raise @command.LaunchFailure {
  match starter {
    Some(starter) =>
      @server.find_or_start(folder, starter) catch {
        error => raise wait_failure(error)
      }
    None =>
      match @server.find(folder) {
        Some(found) =>
          found.server() catch {
            error => raise call_failure(error)
          }
        None =>
          raise NoRuntime(
            "No server runs, and this command cannot start one in the background, because moonrun and moonx are not on the PATH.",
          )
      }
  }
}

///|
impl @command.Launcher for MachineLauncher with fn start(
  self,
  name,
  choice,
  late~,
) {
  let folder = self.base().instance(name)
  let starter = self.starter(name, choice)
  self.remember(with_late_line(late, () => find_or_start(folder, starter)))
}

///|
/// Waits for a server. A person who looks at the terminal gets the late line when the
/// wait needs more than a second.
async fn with_late_line(
  late : async () -> Unit noraise,
  wait : async () -> @server.RunningServer raise @command.LaunchFailure,
) -> @server.RunningServer raise @command.LaunchFailure {
  let is_terminal = stderr_is_terminal()
  @async.with_task_group(group => {
    if is_terminal {
      group.spawn_bg(no_wait=true, () => {
        @async.sleep(late_limit)
        late()
      })
    }
    wait()
  }) catch {
    error => raise launch_failure(error)
  }
}

///|
impl @command.Launcher for MachineLauncher with fn start_desktop(
  self,
  name,
  folder~,
  late~,
) {
  let base = self.base()
  let folder = match folder {
    Some(folder) =>
      Some(@server.existing_folder(folder)) catch {
        Refusal(text) => raise Refused(text)
      }
    None => None
  }
  let programs = @core.desktop_candidates(
    base,
    name,
    @contracts.Channel::current(),
    self.env_vars,
  )
  guard first_program(programs, self.platform) is Some(program) else {
    raise DesktopMissing(
      asked=match self.env_vars.get(@core.desktop_variable) {
        Some("") | None => None
        asked => asked
      },
    )
  }
  // The reason of an older failure is one of another start.
  let since = @app.UnixMillis(@env.now().reinterpret_as_int64()) catch {
    _ => raise NotStarted(reason="The clock is before 1970.", log=None)
  }
  launch_desktop(program, OpenWindow(instance=Some(name), folder~))
  self.remember(
    with_late_line(late, () => {
      @server.wait_for(base.instance(name), since~) catch {
        error => raise wait_failure(error)
      }
    }),
  )
}

///|
/// The first program that is there.
async fn first_program(
  programs : ReadOnlyArray[@core.FolderPath],
  platform : @core.Platform,
) -> String? noraise {
  for program in programs {
    let path = program.to_string()
    if is_program(path, platform) {
      return Some(path)
    }
  }
  None
}

///|
/// Starts the desktop app. It continues when this program and its terminal end. It has
/// the working directory of the user, because it opens the nearest project of that
/// folder when the user gives no folder.
async fn launch_desktop(
  program : String,
  command : @desktop.DesktopCommand,
) -> Unit raise @command.LaunchFailure {
  let starter : @server.Starter = { program, args: command.to_arguments(), }
  let (file, args) = starter.background_command()
  (spawn_silent(file, args[:], None) |> ignore) catch {
    error => raise DesktopNotStarted(path=program, reason="\{error}")
  }
}

///|
/// The failure in an error of a task group.
fn launch_failure(error : Error) -> @command.LaunchFailure {
  match error {
    @command.LaunchFailure::PortInUse(port) => PortInUse(port)
    @command.LaunchFailure::NotStarted(reason~, log~) =>
      NotStarted(reason~, log~)
    @command.LaunchFailure::NotReachable(text) => NotReachable(text)
    @command.LaunchFailure::Refused(text) => Refused(text)
    @command.LaunchFailure::NoRuntime(text) => NoRuntime(text)
    error => NotStarted(reason="\{error}", log=None)
  }
}

///|
/// What `status` says about a server.
async fn describe(
  found : @server.FoundServer,
) -> @command.FoundInstance noraise {
  try {
    let server = found.server()
    let views = @output.Count(server.views())
    let info : @command.ServerInfo = {
      instance: server.instance(),
      version: server.version(),
      port: server.port(),
    }
    @command.FoundInstance::Running(info, views~)
  } catch {
    @server.ServerCallError::Refused(reason)
    | @server.ServerCallError::NotReachable(reason)
    | @server.ServerCallError::BadReply(reason) => NoAnswer(reason~)
    error => NoAnswer(reason="\{error}")
  }
}

///|
impl @command.Launcher for MachineLauncher with fn running(self, name) {
  let base = self.base()
  let found = match name {
    Some(name) =>
      match @server.find(base.instance(name)) {
        Some(found) => [found]
        None => []
      }
    None =>
      @server.find_all(base) catch {
        NotReadable(path~, reason~) => raise NotReadable(path~, reason~)
      }
  }
  let instances = []
  for server in found {
    instances.push(describe(server))
  }
  instances
}

///|
impl @command.Launcher for MachineLauncher with fn link(
  self,
  info,
  surface,
  project,
) {
  let server = self.server_of(info)
  server.link(surface, project) catch {
    error => raise call_failure(error)
  }
}

///|
impl @command.Launcher for MachineLauncher with fn call(
  self,
  info,
  name,
  request,
) {
  let server = self.server_of(info)
  server.call_json(name, request) catch {
    error => raise call_failure(error)
  }
}

///|
impl @command.Launcher for MachineLauncher with fn stop(self, name) {
  guard @server.find(self.base().instance(name)) is Some(found) else {
    return WasNotRunning
  }
  found.server().stop() catch {
    error => raise call_failure(error)
  }
  WasStopped
}

///|
impl @command.Launcher for MachineLauncher with fn serve(
  self,
  name,
  choice,
  ready~,
) {
  let folder = self.base().instance(name)
  let options : @server.ServeOptions = {
    folder,
    port: choice,
    version: @contracts.version(),
  }
  @server.serve(options, reads=self.reads, server => {
    ready(self.remember(server))
  }) catch {
    NotStarted(failure) => raise start_failure(failure)
    Ended(reason) => raise Ended(reason)
    AlreadyRunning =>
      match @server.find(folder) {
        Some(found) => {
          let server = found.server() catch {
            error => raise call_failure(error)
          }
          raise AlreadyRunning(self.remember(server))
        }
        None =>
          raise NotStarted(
            reason="Another server of the instance \{name.to_string()} ended at the same time. Run the command again.",
            log=None,
          )
      }
  }
}

///|
impl @command.Launcher for MachineLauncher with fn open_browser(self, link) {
  match browser_commands(@async.platform, link, self.env_vars) {
    Err(outcome) => outcome
    Ok(commands) => {
      let home = self.home()
      open_with(commands, command => {
        launch_browser(command, home, self.env_vars, self.platform)
      })
    }
  }
}

///|
/// The home folder of the user, if it is there.
async fn MachineLauncher::home(self : MachineLauncher) -> String? noraise {
  let variable = match self.platform {
    Windows => "USERPROFILE"
    MacOs | Linux => "HOME"
  }
  guard self.env_vars.get(variable) is Some(path) &&
    (@fs.kind(path) catch { _ => return None }) is Directory else {
    return None
  }
  Some(path)
}