///|
/// The folder of a project that the server gave. `None` when its path is not an
/// absolute path on the platform.
fn project_folder(project : @app.Project, platform : Platform) -> FolderPath? {
  Some(FolderPath::FolderPath(project.path, platform)) catch {
    EmptyPath | RelativePath(_) => None
  }
}

///|
/// The nearest project that contains the folder: the project folder that is the
/// deepest one. A project whose path does not parse on the platform of the
/// folder is ignored.
pub fn nearest_project(
  projects : ArrayView[@app.Project],
  current : FolderPath,
) -> @app.Project? {
  let mut nearest : (@app.Project, FolderPath)? = None
  for project in projects {
    guard project_folder(project, current.platform) is Some(folder) &&
      folder.contains(current) else {
      continue
    }
    // When two folders contain the current folder, one of them contains the
    // other one. The inner one is nearer.
    if nearest is Some((_, best)) && !best.contains(folder) {
      continue
    }
    nearest = Some((project, folder))
  }
  nearest.map(found => found.0)
}

///|
/// The project that the user opened last. For equal times it is the later one in
/// the list. `None` when the user opened no project.
pub fn last_opened(projects : ArrayView[@app.Project]) -> @app.Project? {
  let mut last : (@app.Project, Int64)? = None
  for project in projects {
    guard project.opened is Some(opened) else { continue }
    let time = opened.to_int64()
    if last is Some((_, latest)) && time < latest {
      continue
    }
    last = Some((project, time))
  }
  last.map(found => found.0)
}

///|
/// How a person names a project on the command line.
///
/// `find` compares names and titles using the platform's case rule: Windows
/// ignores letter case, while Linux and macOS compare exact text.
#derive(Eq, Debug)
pub(all) enum ProjectRef {
  /// Full `urn:mc:proj:...` URN identifier.
  ById(@app.ProjectId)
  /// Absolute or relative folder path.
  ByPath(FolderPath)
  /// Unique short ID (`-`), display title, or folder name.
  ByName(String)
}

///|
/// Raised when a text does not select one project.
#derive(Eq, Debug)
pub(all) suberror ProjectRefError {
  /// No project has this ID, path, short ID, title or name.
  NoMatch(String)
  /// More than one project matches. The projects are in the order of the list.
  Ambiguous(String, ReadOnlyArray[@app.Project])
  /// The text is empty, starts with `urn:mc:proj:` but is not a valid URN, or
  /// has a separator and is not a path.
  InvalidRef(String)
}

///|
/// Reads the text that a person gives for a project.
///
/// - A text starting with `urn:mc:proj:` is parsed as a `ProjectId` URN.
/// - A text that is `.` or `..`, or that has a separator of the platform, is a
///   path. A relative path starts at the current folder.
/// - Each other non-empty text matches a unique short ID, display title, or
///   folder name.
pub fn ProjectRef::ProjectRef(
  text : String,
  current : FolderPath,
) -> ProjectRef raise ProjectRefError {
  guard text != "" else { raise InvalidRef(text) }
  if text.has_prefix("urn:mc:proj:") {
    let id = @app.ProjectId::ProjectId(text) catch {
      _ => raise InvalidRef(text)
    }
    ById(id)
  } else if text == "." ||
    text == ".." ||
    text.iter().any(c => is_separator(c, current.platform)) {
    let folder = FolderPath::resolve(text, current) catch {
      EmptyPath | RelativePath(_) => raise InvalidRef(text)
    }
    ByPath(folder)
  } else {
    ByName(text)
  }
}

///|
/// Finds the project in the list. `NoMatch` names the ID, the complete path or
/// the name. The folder of the project can be missing on the disk.
pub fn ProjectRef::find(
  self : ProjectRef,
  projects : ArrayView[@app.Project],
) -> @app.Project raise ProjectRefError {
  let (text, matches) = match self {
    ById(id) => (id.to_string(), projects.filter(project => project.id == id))
    ByPath(folder) =>
      (
        folder.to_string(),
        projects.filter(project => {
          project_folder(project, folder.platform) is Some(other) &&
          other.same_folder(folder)
        }),
      )
    ByName(name) => {
      // Exact unique short-ID match wins before display-title / folder-name matching.
      let by_short = projects.filter(project => project.id.short_id() == name)
      if !by_short.is_empty() {
        (name, by_short)
      } else {
        (
          name,
          projects.filter(project => project_has_name_or_title(project, name)),
        )
      }
    }
  }
  match matches {
    [] => raise NoMatch(text)
    [project] => project
    _ => raise Ambiguous(text, ReadOnlyArray::from_array(matches))
  }
}

///|
/// True when the project's display title or folder/repository name matches
/// `name` under the platform's case rule.
fn project_has_name_or_title(project : @app.Project, name : String) -> Bool {
  let platform = match project_folder(project, Linux) {
    Some(_) => Linux
    None =>
      match project_folder(project, Windows) {
        Some(_) => Windows
        None => Linux
      }
  }
  let cmp = (a : String, b : String) => {
    match platform {
      Windows => a.to_lower() == b.to_lower()
      MacOs | Linux => a == b
    }
  }
  cmp(project.title.to_string(), name) || cmp(project.name, name)
}

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

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

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

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