///|
/// Run the host without ending the process. Hooks share one context and services
/// record. Start hooks run in registration order, stop hooks in reverse order.
/// Stop requests cancel the command task and its defers finish before shutdown.
/// Shutdown runs protected from outside cancellation, within one time budget.
/// It reports each shutdown timeout for every exit code, and other failures only
/// for code 1 or 2, in failure order, through `error_report` or as
/// `: ` on standard error. Report errors do not change the outcome.
///
/// A help or version request of the arguments writes the argparse text one
/// time with `println` and returns code 0 with the reason `Requested`, before
/// the configuration load, the factory and the hooks. The console driver then
/// ends the process with that code.
///
/// A console driver gives `signals`. The run registers the probe before the
/// first hook, so each cancellation check reads it, and a watcher task reads it
/// every 50 ms until the run ends. The first signal is a stop request with the
/// reason `Signal(kind)`, and it cancels the command task.
///
/// `cancellation` names the stop that a cancellation of the calling task gives
/// before the stop phase. The default is a stop request with the reason
/// `Requested`. The Moonrun driver gives `AsUnidentifiedSignal`, because
/// `moonbitlang/core/async` gives a signal on wasm only as the cancellation of
/// the event loop (interim). The stop phase stays protected from cancellation.
pub async fn[S] run(
  host : Host[S],
  command : Hook[S],
  signals? : SignalProbe,
  cancellation~ : CancellationStop = AsRequest,
) -> RunOutcome {
  run_with_directory_reader(host, command, signals?, cancellation~)
}

///|
/// Run a host whose services record implements `Program`, without ending the
/// process.
pub async fn[S : Program] run_app(
  host : Host[S],
  signals? : SignalProbe,
  cancellation~ : CancellationStop = AsRequest,
) -> RunOutcome {
  run(host, ctx => S::run(ctx.services, ctx), signals?, cancellation~)
}

///|
/// The time between two reads of the signal probe by the watcher task.
let signal_watch_interval : Int32 = 50

///|
async fn report_outcome_failures(
  name : @lander_core.AppName,
  report : ErrorReport?,
  writer : ReportWriter?,
  result : RunOutcome,
) -> Unit {
  @async.protect_from_cancel(() => {
    for error in result.failures {
      if error is ShutdownTimedOut(_) ||
        result.exit_code == ExitCode::failure() ||
        result.exit_code == usage_exit_code() {
        try {
          match report {
            Some(report) => report(error, result.exit_code)
            None =>
              match writer {
                Some(writer) => writer(report_text(name, error))
                None => write_report_line(report_text(name, error))
              }
          }
        } catch {
          _ => ()
        }
      }
    }
  })
}

///|
async fn[S] run_with_directory_reader(
  host : Host[S],
  command : Hook[S],
  read_directory~ : () -> @lander_core.AbsolutePath raise WorkingDirectoryError = process_directory,
  signals? : SignalProbe,
  cancellation~ : CancellationStop = AsRequest,
) -> RunOutcome {
  let result = execute(host, command, read_directory~, signals?, cancellation~)
  report_outcome_failures(host.name, host.report, host.report_writer, result)
  result
}

///|
async fn[S] run_engine_with_signals(
  host : Host[S],
  configured : ConfiguredRun[S],
  command : Hook[S],
  signals : SignalProbe?,
  cancellation~ : CancellationStop,
) -> RunOutcome {
  let ctx = configured.context
  let lifetime = ctx.lifetime
  guard signals is Some(probe) else {
    return run_engine(host, configured, command, cancellation~)
  }
  lifetime.register_stop_probe(probe.request)
  with_group(group => {
    group.spawn_bg(no_wait=true, () => {
      while true {
        @async.sleep(signal_watch_interval)
        ignore(lifetime.probe_stop())
      }
    })
    run_engine(host, configured, command, cancellation~)
  })
}

///|
/// Run a host builder with an enclosing async setup step that executes only
/// after CLI argument parsing and configuration load succeed.
///
/// When `--help`/`--version` is requested or argument parsing / configuration
/// loading fails, `setup` is not called, any failures are reported through the
/// standard reporter, and `(outcome, None)` is returned.
///
/// Inside `setup(ctx, proceed)`, calling `proceed(make_services, report_writer)`
/// builds services, executes hooks and the command, reports failures through
/// `report_writer` (or the builder's `error_report` / stderr), and returns the
/// `RunOutcome`. If `setup` raises before returning, the error is reported
/// through the builder's standard reporter and `(outcome, None)` is returned.
pub async fn[S, X] run_with_setup(
  builder : HostBuilder[S],
  command : Hook[S],
  setup : async (
    BuildContext,
    async (() -> S raise, ReportWriter?) -> RunOutcome,
  ) -> (RunOutcome, X),
  signals? : SignalProbe,
  cancellation~ : CancellationStop = AsRequest,
) -> (RunOutcome, X?) {
  let shell : Host[S] = build(builder, _ => {
    abort("shell host factory is never called")
  })
  let inputs = configuration_inputs(shell) catch {
    DisplayRequested(text) => {
      println(text)
      return (with_signal(requested_outcome(), signals), None)
    }
    err => {
      let result = with_signal(outcome(err), signals)
      report_outcome_failures(shell.name, shell.report, None, result)
      return (result, None)
    }
  }
  let config = load_configuration(shell, inputs.sources) catch {
    err => {
      let result = with_signal(outcome(err), signals)
      report_outcome_failures(shell.name, shell.report, None, result)
      return (result, None)
    }
  }
  let shutdown_timeout = resolve_shutdown_timeout(shell, config) catch {
    err => {
      let result = with_signal(outcome(err), signals)
      report_outcome_failures(shell.name, shell.report, None, result)
      return (result, None)
    }
  }
  let build_ctx = build_context_of(inputs, config)
  let started = Ref(false)
  let recorded : Ref[RunOutcome?] = Ref(None)
  let proceed = async fn(
    make_services : () -> S raise,
    writer : ReportWriter?,
  ) -> RunOutcome {
    if started.val {
      match recorded.val {
        Some(existing) => return existing
        None => return with_signal(requested_outcome(), signals)
      }
    }
    started.val = true
    let result = match (Ok(make_services()) catch { err => Err(err) }) {
      Ok(services) => {
        let configured = configured_run_of(
          build_ctx, services, shutdown_timeout,
        )
        run_engine_with_signals(
          shell,
          configured,
          command,
          signals,
          cancellation~,
        )
      }
      Err(StopRequested) => with_signal(requested_outcome(), signals)
      Err(err) => with_signal(outcome(err), signals)
    }
    report_outcome_failures(shell.name, shell.report, writer, result)
    recorded.val = Some(result)
    result
  }
  let (result, extra) = setup(build_ctx, proceed) catch {
    StopRequested =>
      match recorded.val {
        Some(existing) => return (with_signal(existing, signals), None)
        None => return (with_signal(requested_outcome(), signals), None)
      }
    err =>
      match recorded.val {
        Some(existing) => {
          let failures = [..existing.failures, err]
          let combined_signal = match existing.signal {
            Some(kind) => Some(kind)
            None =>
              match signals {
                Some(probe) =>
                  match (probe.request)() {
                    Some(Signal(kind)) => Some(kind)
                    _ => None
                  }
                None => None
              }
          }
          let merged : RunOutcome = {
            ..existing,
            signal: combined_signal,
            failures,
            exit_code: select_exit_code(
              combined_signal,
              failures,
              existing.timed_out,
              existing.requested_code,
            ),
          }
          let cleanup_only : RunOutcome = { ..merged, failures: [err], }
          report_outcome_failures(shell.name, shell.report, None, cleanup_only)
          return (merged, None)
        }
        None => {
          let result = with_signal(outcome(err), signals)
          report_outcome_failures(shell.name, shell.report, None, result)
          return (result, None)
        }
      }
  }
  (result, Some(extra))
}

///|
async fn[S] execute(
  host : Host[S],
  command : Hook[S],
  read_directory~ : () -> @lander_core.AbsolutePath raise WorkingDirectoryError,
  signals? : SignalProbe,
  cancellation~ : CancellationStop,
) -> RunOutcome {
  let inputs = configuration_inputs(host, read_directory~) catch {
    DisplayRequested(text) => {
      println(text)
      return with_signal(requested_outcome(), signals)
    }
    err => return with_signal(outcome(err), signals)
  }
  let config = load_configuration(host, inputs.sources) catch {
    err => return with_signal(outcome(err), signals)
  }
  let configured = finish_configuration(host, inputs, config) catch {
    StopRequested => return with_signal(requested_outcome(), signals)
    err => return with_signal(outcome(err), signals)
  }
  run_engine_with_signals(host, configured, command, signals, cancellation~)
}

///|
/// A signal that arrived before the engine started still selects the exit code.
/// The reason stays the first event of the run.
fn with_signal(result : RunOutcome, signals : SignalProbe?) -> RunOutcome {
  guard signals is Some(probe) && (probe.request)() is Some(Signal(kind)) else {
    return result
  }
  { ..result, signal: Some(kind), exit_code: kind.exit_code(), }
}

///|
async fn[S] run_engine(
  host : Host[S],
  configured : ConfiguredRun[S],
  command : Hook[S],
  cancellation~ : CancellationStop,
) -> RunOutcome {
  let ctx = configured.context
  let lifetime = ctx.lifetime
  lifetime.task_cancelled.val = @async.is_being_cancelled
  defer {
    lifetime.task_cancelled.val = () => false
  }
  let mut step = lifetime.start_engine(host.services)
  while step is Run(pending, action) {
    if action == Raise(Stopping) {
      break
    }
    step = run_step(host, ctx, command, pending, action, cancellation~)
  }
  if @async.is_being_cancelled() {
    stop_after_cancellation(lifetime, cancellation)
  }
  @async.protect_from_cancel(() => {
    let mut interrupted = ActionResult::Interrupted
    // The timeout cancels the hooks. A hook can absorb that cancellation and
    // return, and then `with_timeout_opt` gives the result of the body. So the
    // body gives `false` when it stops because of the cancellation.
    let completed = @async.with_timeout_opt(
      configured.shutdown_timeout.to_millis(),
      () => {
        while step is Run(pending, action) {
          let result = perform_step(
            host,
            ctx,
            command,
            pending,
            action,
            cancellation=AsRequest,
          )
          // Keep the current token for timed_out, even if a hook absorbs cancellation.
          if @async.is_being_cancelled() {
            interrupted = result.unwrap_or(Interrupted)
            return false
          }
          step = reply_step(ctx, pending, result, cancellation=AsRequest)
        }
        true
      },
    )
    if !(completed is Some(true)) && step is Run(pending, _) {
      ignore(lifetime.probe_stop())
      step = pending.timed_out(
        limit=configured.shutdown_timeout,
        observed_signal?=lifetime.signal,
        result=interrupted,
      )
    }
    // The timeout reply skips hooks and leaves only the stopped event.
    while step is Run(pending, action) {
      step = run_step(
        host,
        ctx,
        command,
        pending,
        action,
        cancellation=AsRequest,
      )
    }
  })
  guard step is Finish(result) else {
    abort("the engine finishes after its last action")
  }
  lifetime.reason = Some(result.reason)
  {
    ..result,
    exit_code: select_exit_code(
      result.signal,
      result.failures,
      result.timed_out,
      match lifetime.exit_code {
        Some(code) => Some(code)
        None => result.requested_code
      },
    ),
  }
}

///|
async fn[S] run_step(
  host : Host[S],
  ctx : Context[S],
  command : Hook[S],
  pending : Pending,
  action : Action,
  cancellation~ : CancellationStop,
) -> Step {
  reply_step(
    ctx,
    pending,
    perform_step(host, ctx, command, pending, action, cancellation~),
    cancellation~,
  )
}

///|
async fn[S] perform_step(
  host : Host[S],
  ctx : Context[S],
  command : Hook[S],
  pending : Pending,
  action : Action,
  cancellation~ : CancellationStop,
) -> ActionResult? {
  let lifetime = ctx.lifetime
  if pending.engine.reason is Some(reason) {
    lifetime.reason = Some(reason)
  }
  @async.handle_cancellation(() => {
    try {
      match action {
        Hook(reference, phase) =>
          if host.services[reference.index].hook(phase) is Some(hook) {
            hook(ctx)
          }
        RunCommand => run_command(ctx, command, cancellation~)
        Raise(event) => lifetime.raise_event(event)
      }
      ActionResult::Returned
    } catch {
      StopRequested => {
        stop_after_cancellation(lifetime, cancellation)
        Interrupted
      }
      error => Failed(error)
    }
  })
}

///|
fn[S] reply_step(
  ctx : Context[S],
  pending : Pending,
  completed : ActionResult?,
  cancellation~ : CancellationStop,
) -> Step {
  if completed is None {
    stop_after_cancellation(ctx.lifetime, cancellation)
  }
  ctx.lifetime.reply(pending, completed.unwrap_or(Interrupted))
}

///|
async fn[S] run_command(
  ctx : Context[S],
  command : Hook[S],
  cancellation~ : CancellationStop,
) -> Unit {
  let lifetime = ctx.lifetime
  with_group(group => {
    let task = group.spawn(() => command(ctx), allow_failure=true)
    lifetime.cancel_command.val = Some(() => task.cancel())
    defer {
      lifetime.cancel_command.val = None
    }
    if lifetime.probe_stop() {
      task.cancel()
    }
    task.wait() catch {
      @async.WaitedTaskAlreadyCancelled =>
        stop_after_cancellation(lifetime, cancellation)
      error => raise error
    }
  })
}

///|
/// Make the stop request of a cancellation. Before the stop phase, a stop
/// request cancels only the command task, so a cancellation of the task of the
/// run comes from outside the run. With `AsUnidentifiedSignal`, that
/// cancellation is a stop request with the reason `Signal(Unidentified)`. Any
/// other cancellation, and every cancellation in the stop phase, is a stop
/// request with the reason `Requested`.
fn stop_after_cancellation(
  lifetime : Lifetime,
  cancellation : CancellationStop,
) -> Unit {
  match cancellation {
    AsUnidentifiedSignal if @async.is_being_cancelled() =>
      lifetime.request_stop(Signal(Unidentified), None)
    _ => lifetime.stop_application()
  }
}

///|
/// Run `body` in a new task group and return its result. The task group of
/// `moonbitlang/core/async` gives no result, so this keeps the one of `body`.
async fn[X] with_group(body : async (@async.TaskGroup) -> X) -> X {
  let result : Ref[X?] = { val: None, }
  @async.with_task_group(group => result.val = Some(body(group)))
  result.val.unwrap()
}