///|
/// The path of a folder that exists, as the project list has it. It follows each link
/// and has the letters that the file system has, so two ways to write one folder give one
/// path.
///
/// Raises the error of the system. Raises `FolderPathError` with the real path when a
/// project cannot have it.
async fn real_path(folder : @core.FolderPath) -> @core.FolderPath {
  @core.FolderPath(
    // Windows can give a path with the prefix `\\?\`. The parser removes it.
    @fs.realpath(folder.to_string()),
    machine_platform(),
  )
}

///|
/// The platform whose rules read the paths of this machine.
fn machine_platform() -> @core.Platform {
  match @async.platform {
    Windows => Windows
    MacOS => MacOs
    Linux => Linux
  }
}

///|
/// The path that the project list has for a folder that a user names, such as a link.
///
/// When the folder is gone, the result is the real path of the nearest folder above it
/// that exists, with the other names. So a user can still name a project whose folder is
/// gone. When the system gives no answer in a second, such as for a network share that
/// is off, the result is the path of the user.
///
/// The read then continues in the group `reads`, and nothing can cancel it. So the
/// program must end with `@env.exit`, as after `serve`.
pub async fn[X] real_folder(
  folder : @core.FolderPath,
  reads~ : @async.TaskGroup[X],
) -> @core.FolderPath noraise {
  limited_folder(folder, reads~, limit=state_limit, read=real_or_given)
}

///|
async fn real_or_given(folder : @core.FolderPath) -> @core.FolderPath noraise {
  real_path(folder) catch {
    error if is_missing(error) =>
      try {
        let above = @core.FolderPath::resolve("..", folder)
        // Nothing is above the root.
        guard above != folder else { folder }
        @core.FolderPath::resolve(folder.name(), real_or_given(above))
      } catch {
        _ => folder
      }
    _ => folder
  }
}

///|
/// Reads a path in the group, and waits for the answer until the limit. Without an
/// answer, the result is the path that was given.
async fn[X] limited_folder(
  folder : @core.FolderPath,
  reads~ : @async.TaskGroup[X],
  limit~ : Duration,
  read~ : async (@core.FolderPath) -> @core.FolderPath noraise,
) -> @core.FolderPath noraise {
  let answer = Ref(None)
  let end = @cond_var.Cond()
  reads.spawn_bg(no_wait=true, () => {
    answer.val = Some(read(folder))
    end.broadcast()
  })
  (@async.with_timeout_opt(limit.millis(), () => {
    while answer.val is None {
      end.wait()
    }
  })
  |> ignore) catch {
    // The command ends. A wait raises nothing else.
    _ => ()
  }
  answer.val.unwrap_or(folder)
}