///|
/// The program that runs the server of an instance: the CLI or the desktop app, with
/// the arguments of `serve`. A start fails when the program ends, so a program that
/// starts another one must wait for it.
#derive(Eq, Debug)
pub(all) struct Starter {
  /// The full path of the program. A start with another text fails, because Windows looks
  /// for a name in the working directory first.
  program : String
  args : ReadOnlyArray[String]
}

///|
/// The reason why there is no server of the instance.
#derive(Eq, Debug)
pub(all) suberror StartError {
  /// Another program uses the port.
  PortInUse(@core.Port)
  /// Each other reason, as a text for people, with the last lines of the server log and
  /// the path of the log.
  Failed(reason~ : String, log_tail~ : ReadOnlyArray[String], log~ : String)
}

///|
/// How long a server has to answer after its start, and how long a start waits for a
/// server or another start that is late.
let start_limit : Duration = Duration(10_000)

///|
/// The number of lines in `log_tail`.
let log_tail_lines : Int32 = 20

///|
/// The last part of the log in which the lines of `log_tail` are, in bytes.
let log_tail_bytes : Int32 = 65_536

///|
/// Finds the server of an instance, or starts one in the background and waits until it
/// answers. The server continues when this program and its terminal end.
///
/// When two programs do this at the same time, one of them starts a server, and the
/// other one waits for it. Both get the same server.
///
/// This needs about 20 seconds at most: 10 seconds for a server that stops or for another
/// start, and 10 seconds for the new server to answer. The error comes at once when the
/// new server ends or writes the reason of its failure. A server that does not answer
/// in time continues to run, so a later command can find it.
///
/// The server gets the folder of the instance as its working directory,
/// `MISSION_CONTROL_BACKGROUND=1`, no input, and `server.log` for both outputs. It has
/// no other file or pipe of this program, so a program that reads the output of this
/// one does not wait for the server.
pub async fn find_or_start(
  folder : @core.InstanceFolder,
  starter : Starter,
) -> RunningServer raise StartError {
  find_or_start_with(folder, () => spawn_server(folder, starter), start_limit)
}

///|
/// Waits until the server of an instance answers, for 10 seconds at most. Another
/// program starts the server, such as the desktop app. `since` is a time before that
/// start: the reason of an older failure does not count.
pub async fn wait_for(
  folder : @core.InstanceFolder,
  since~ : @app.UnixMillis,
) -> RunningServer raise StartError {
  wait_for_in(folder, since~, start_limit)
}

///|
/// Finds or starts a server. `spawn` starts the process and gives its ID. `limit` is
/// the limit of each of the two waits.
async fn find_or_start_with(
  folder : @core.InstanceFolder,
  spawn : async () -> Int32 raise StartError,
  limit : Duration,
) -> RunningServer raise StartError {
  let end = limit.after(@async.now())
  for ;; {
    let left = Duration::between(@async.now(), end)
    match find_in(folder, left) {
      Some(Answers(server)) => return server
      Some(NewerFormat(name, format)) =>
        raise failed(folder, newer_format_text(name, format))
      Some(Silent(_)) | None => ()
    }
    let turn = take_turn(folder) catch {
      error => raise failed(folder, "\{folder.log()}: \{reason_of(error)}")
    }
    if turn is Some(turn) {
      defer turn.close()
      let is_free = lock_is_free(folder) catch {
        error => raise failed(folder, "\{folder.lock()}: \{reason_of(error)}")
      }
      if is_free {
        return start(folder, spawn, limit)
      }
    }
    guard @async.now() < end else {
      raise failed(
        folder,
        "A server of the instance \{folder.name().to_string()} runs or starts, but it did not answer in \{limit.to_text()}.",
      )
    }
    @async.sleep(look_delay.millis())
  }
}

///|
/// Takes the right to start a server, if no other program has it. It is a lock on
/// `server.log`, so a second start waits, and does not replace the log of the first
/// one. The system releases the lock when the file closes or the program ends.
async fn take_turn(folder : @core.InstanceFolder) -> @fs.File? {
  make_private_folder(folder.path())
  let file = retry_in_use(() => {
    @fs.open(
      folder.log(),
      mode=ReadWrite,
      create_mode=OpenOrCreate,
      permission=private_file_mode,
    )
  })
  errdefer file.close()
  if file.try_lock(Exclusive) {
    Some(file)
  } else {
    file.close()
    None
  }
}

///|
/// Starts a server and waits for its answer. The caller has the right to start it.
async fn start(
  folder : @core.InstanceFolder,
  spawn : async () -> Int32 raise StartError,
  limit : Duration,
) -> RunningServer raise StartError {
  let since = system_time()
  let pid = spawn()
  let has_ended = Ref(false)
  @async.with_task_group(group => {
    group.spawn_bg(no_wait=true, () => has_ended.val = wait_for_end(pid))
    wait_for_answer(folder, since~, limit, has_ended)
  }) catch {
    PortInUse(port) => raise PortInUse(port)
    Failed(..) as error => raise error
    error => raise failed(folder, reason_of(error))
  }
}

///|
/// Waits for the answer of a server that another program starts.
async fn wait_for_in(
  folder : @core.InstanceFolder,
  since~ : @app.UnixMillis,
  limit : Duration,
) -> RunningServer raise StartError {
  wait_for_answer(folder, since~, limit, Ref(false))
}

///|
/// Waits until a server answers, or until it is clear that none does. `has_ended` says
/// if the process of the new server ended.
async fn wait_for_answer(
  folder : @core.InstanceFolder,
  since~ : @app.UnixMillis,
  limit : Duration,
  has_ended : Ref[Bool],
) -> RunningServer raise StartError {
  let end = limit.after(@async.now())
  for ;; {
    // This comes before the look at the files: a process writes its record and then
    // ends.
    let ended = has_ended.val
    let look = look_at(folder)
    if look is Found(Answers(server)) {
      return server
    }
    if read_record(folder) is Known(Failed(at~, failure~)) &&
      at.to_int64() >= since.to_int64() {
      raise start_failure(folder, failure)
    }
    // When a process has the lock, the user runs `serve` at the same time.
    if ended && (lock_is_free(folder) catch { _ => false }) {
      raise failed(folder, "The server ended during its start.")
    }
    guard @async.now() < end else {
      let reason = match look {
        // Another program started a newer version.
        Found(NewerFormat(name, format)) => newer_format_text(name, format)
        _ => "The server did not answer in \{limit.to_text()}."
      }
      raise failed(folder, reason)
    }
    @async.sleep(look_delay.millis())
  }
}

///|
/// The error for a failure in the record.
async fn start_failure(
  folder : @core.InstanceFolder,
  failure : @core.StartFailure,
) -> StartError noraise {
  match failure {
    PortInUse(port) => PortInUse(port)
    BadProjectFile(path~, message~) =>
      failed(folder, "\{path} cannot be used. \{message}")
    Other(reason) => failed(folder, reason)
  }
}

///|
/// The error with the log of the server.
async fn failed(
  folder : @core.InstanceFolder,
  reason : String,
) -> StartError noraise {
  Failed(reason~, log_tail=last_log_lines(folder), log=folder.log())
}

///|
/// The last lines of the log, without their line ends. There are none without a log.
async fn last_log_lines(
  folder : @core.InstanceFolder,
) -> ReadOnlyArray[String] noraise {
  let text = read_end(folder.log(), log_tail_bytes) catch { _ => "" }
  let lines = text
    .split("\n")
    .map(line => line.trim_end(chars="\r").to_owned())
    .collect()
  if lines.last() is Some("") {
    ignore(lines.pop())
  }
  let start = (lines.length() - log_tail_lines).max(0)
  ReadOnlyArray::from_array(lines[start:])
}

///|
/// The last bytes of a file as text. The first character can be broken.
async fn read_end(path : String, size : Int32) -> String {
  let file = @fs.open(path, mode=ReadOnly)
  defer file.close()
  let length = file.size().min(size.to_int64())
  let start = file.size() - length
  @utf8.decode_lossy(file.read_exactly_at(length.to_int(), position=start))
}

///|
/// Waits for the end of a process that this program started. Gives false when the
/// system cannot say it. Then only the limit of the start ends the wait.
///
/// Call it at once after the start. On Windows with the wasm runtime,
/// `@process.wait_pid` ends this program when the process is not there. This is a defect
/// of `moonbitlang/async` (0.22.10): it must raise an error, as on native.
async fn wait_for_end(pid : Int32) -> Bool noraise {
  try @process.wait_pid(pid) catch {
    @os_error.OSError(code, ..) =>
      match @async.platform {
        // ERROR_INVALID_PARAMETER: the process is not there any more.
        Windows => code == 87
        // ESRCH and ECHILD.
        Linux | MacOS => code is (3 | 10)
      }
    _ => false
  } noraise {
    _ => true
  }
}

///|
/// Starts the process of a server in the background, and gives its ID. It replaces the
/// log.
async fn spawn_server(
  folder : @core.InstanceFolder,
  starter : Starter,
) -> Int32 raise StartError {
  (@core.FolderPath::FolderPath(starter.program, folder.platform()) |> ignore) catch {
    _ =>
      raise failed(
        folder,
        "\{starter.program} does not start: It is not a full path.",
      )
  }
  // Without this, `sh` says it, and only in the log.
  if !(@async.platform is Windows) {
    (@fs.kind(starter.program) |> ignore) catch {
      error => raise not_startable(folder, starter, error)
    }
  }
  let (input, log) = try {
    make_private_folder(folder.path())
    let log = open_log(folder)
    errdefer log.close()
    let input = @process.redirect_from_file(
      if @async.platform is Windows {
        "NUL"
      } else {
        "/dev/null"
      },
    )
    (input, log)
  } catch {
    error => raise failed(folder, "\{folder.log()}: \{reason_of(error)}")
  } noraise {
    files => files
  }
  let (program, args) = starter.background_command()
  @process.spawn_orphan(
    program,
    args[:],
    extra_env={ "MISSION_CONTROL_BACKGROUND": "1" },
    stdin=input,
    stdout=log,
    stderr=log,
    cwd=folder.path(),
    no_console_window=true,
  ) catch {
    error => raise not_startable(folder, starter, error)
  }
}

///|
async fn not_startable(
  folder : @core.InstanceFolder,
  starter : Starter,
  error : Error,
) -> StartError noraise {
  failed(folder, "\{starter.program} does not start: \{reason_of(error)}")
}

///|
/// The command that runs a starter in the background: a program with its full path, and
/// its arguments.
///
/// On Linux and macOS, the new process is in the process group of this program. A
/// terminal that closes, Ctrl+C and Ctrl+Z send a signal to the group, when for example
/// `ssh -t` or a script ran this program. `sh` ignores these signals and then becomes the
/// program, with the same process ID. A program inherits the signals that it ignores.
///
/// On Windows, the new process has its own console without a window.
pub fn Starter::background_command(self : Starter) -> (String, Array[String]) {
  match @async.platform {
    Windows => (self.program, self.args.iter().collect())
    Linux | MacOS =>
      (
        "/bin/sh",
        [
          "-c",
          "trap '' HUP INT QUIT TSTP; exec \"$0\" \"$@\"",
          self.program,
          ..self.args,
        ],
      )
  }
}

///|
/// Makes an empty log that only the current user can read, for the outputs of a server.
async fn open_log(folder : @core.InstanceFolder) -> &@process.ProcessOutput {
  let path = folder.log()
  let log = retry_in_use(() => {
    @process.redirect_to_file(path, append=true, permission=private_file_mode)
  })
  errdefer log.close()
  if !(@async.platform is Windows) {
    // An old log keeps its rights.
    @fs.chmod(path, private_file_mode)
  }
  log
}

///|
pub extend Starter with Eq::{not_equal, equal}

///|
pub extend Starter with @debug.Debug::{to_repr}

///|
pub extend StartError with Eq::{not_equal, equal}

///|
pub extend StartError with @debug.Debug::{to_repr}