///|
/// Raised when no project in the list has the ID.
#derive(Eq, Debug)
pub suberror UnknownProject {
  UnknownProject(@app.ProjectId)
}

///|
/// One project entry in the core domain model (zero serialization traits).
#derive(Eq, Debug)
pub struct Entry {
  id : @app.ProjectId
  anchor : Anchor
  title : @app.ProjectTitle
  caption : @app.ProjectCaption?
  /// The time when the user added the project.
  added : @app.UnixMillis
  /// The time when the user opened the project last, if the user opened it.
  opened : @app.UnixMillis?
}

///|
/// The display folder path for this entry (plain folder, enclosing repo root
/// for `.git`, first remembered checkout, or bare store path).
pub fn Entry::folder(self : Entry) -> FolderPath {
  self.anchor.display_folder()
}

///|
/// The folder path checked on disk to compute `Project.folder`.
pub fn Entry::check_folder(self : Entry) -> FolderPath {
  self.anchor.check_folder()
}

///|
/// The VCS backend identifier of this project (`folder`, `git`, etc.).
pub fn Entry::backend(self : Entry) -> @app.BackendId {
  self.anchor.backend()
}

///|
/// The derived folder or repository basename of this project.
pub fn Entry::name(self : Entry) -> String {
  self.anchor.name()
}

///|
/// All workspace roots currently known for this entry (one root for plain
/// folders; remembered checkout roots for repositories).
pub fn Entry::known_roots(self : Entry) -> ReadOnlyArray[FolderPath] {
  match self.anchor {
    Folder(path) => [path]
    Repository(seen~, ..) =>
      ReadOnlyArray::from_iter(seen.items().iter().map(item => item.root))
  }
}

///|
/// Reconciles an entry against a fresh backend `Observation`, updating
/// remembered checkout roots and deriving the exact `DomainProjectWorkspaces`
/// state (`Empty`, `Populated`, or `Unavailable`).
pub fn Entry::reconcile(
  self : Entry,
  observation : Observation,
) -> (Entry, DomainProjectWorkspaces, ReadOnlyArray[DomainEvent]) {
  match self.anchor {
    Folder(path) => {
      let folder_state : @app.FolderState = match observation {
        Checkouts(list) =>
          match list.get(0) {
            Some(c) => c.folder
            None => Missing
          }
        NoAnswer(_) => Missing
      }
      let ws : DomainWorkspace = {
        id: workspace_id_of(path),
        name: default_workspace_name(path),
        root: path,
        backend: @app.BackendId::folder(),
        folder: folder_state,
        position: Unversioned,
        opened: self.opened,
      }
      let set = DomainWorkspaceSet::DomainWorkspaceSet([ws], default_id=ws.id) catch {
        _ => abort("single plain-folder workspace set failed invariant")
      }
      let result = DomainProjectWorkspaces::Populated(set)
      (self, result, [WorkspacesReconciled(self.id, result)])
    }
    Repository(backend~, store~, seen~) =>
      match observation {
        NoAnswer(reason) => {
          let result = DomainProjectWorkspaces::Unavailable(
            reason~,
            remembered=seen.items(),
          )
          (self, result, [WorkspacesReconciled(self.id, result)])
        }
        Checkouts(checkouts) =>
          if checkouts.is_empty() {
            let updated_anchor = Anchor::Repository(
              backend~,
              store~,
              seen=SeenWorkspaces::empty(),
            )
            let updated = { ..self, anchor: updated_anchor, }
            let result = DomainProjectWorkspaces::Empty
            (updated, result, [WorkspacesReconciled(self.id, result)])
          } else {
            let workspaces : Array[DomainWorkspace] = []
            let next_seen : Array[SeenWorkspace] = []
            for checkout in checkouts {
              let ws_id = workspace_id_of(checkout.root)
              if workspaces.iter().any(other => other.id == ws_id) {
                continue
              }
              let opened = match seen.find_root(checkout.root) {
                Some(prev) => prev.opened
                None => None
              }
              workspaces.push({
                id: ws_id,
                name: default_workspace_name(checkout.root),
                root: checkout.root,
                backend,
                folder: checkout.folder,
                position: checkout.position,
                opened,
              })
              next_seen.push({ root: checkout.root, opened, })
            }
            let ws_ro = ReadOnlyArray::from_array(workspaces)
            let default_id = derive_default_workspace_id(ws_ro)
            let set = DomainWorkspaceSet::DomainWorkspaceSet(ws_ro, default_id~) catch {
              _ => abort("reconciled workspace set failed invariant")
            }
            let new_seen = SeenWorkspaces::SeenWorkspaces(next_seen) catch {
              _ => seen
            }
            let updated = {
              ..self,
              anchor: Anchor::Repository(backend~, store~, seen=new_seen),
            }
            let result = DomainProjectWorkspaces::Populated(set)
            (updated, result, [WorkspacesReconciled(self.id, result)])
          }
      }
  }
}

///|
/// The projects of an instance, in the order in which the user added them.
///
/// Each plain folder and each repository store appears at most once. Project
/// IDs are deterministic RFC 8141 URNs derived from each entry's `Anchor`.
#derive(Eq, Debug)
struct ProjectList {
  entries : ReadOnlyArray[Entry]
}

///|
/// The list without projects.
pub fn ProjectList::empty() -> ProjectList {
  { entries: [], }
}

///|
/// Admits a `Located` target (plain folder, checkout, or bare store) into the
/// project list with resolved `title` and optional `caption`.
///
/// If an entry with the same anchor is already listed, returns `Existing` (for
/// a checkout, ensures its root is remembered in `seen`). Otherwise appends a
/// new entry and returns `Added`.
pub fn ProjectList::admit(
  self : ProjectList,
  located : Located,
  title~ : @app.ProjectTitle,
  caption~ : @app.ProjectCaption?,
  now : @app.UnixMillis,
) -> (ProjectList, Admission, ReadOnlyArray[DomainEvent]) {
  let target : @app.AddedTarget = match located {
    PlainFolder(folder) => WorkspaceRoot(workspace_id_of(folder.path()))
    Checkout(root~, ..) => WorkspaceRoot(workspace_id_of(root))
    BareStore(..) => RepositoryOnly
  }
  let candidate_anchor = located.to_anchor()
  for i, existing in self.entries {
    if existing.anchor.same_anchor(candidate_anchor) {
      let updated_entry = match (existing.anchor, located) {
        (Repository(backend~, store~, seen~), Checkout(root~, ..)) => {
          let next_seen = seen.remember(root)
          if next_seen == seen {
            existing
          } else {
            {
              ..existing,
              anchor: Anchor::Repository(backend~, store~, seen=next_seen),
            }
          }
        }
        _ => existing
      }
      let next_list = if updated_entry == existing {
        self
      } else {
        let arr = self.entries.iter().collect()
        arr[i] = updated_entry
        { entries: ReadOnlyArray::from_array(arr), }
      }
      return (
        next_list,
        Existing(updated_entry, target),
        [ProjectAdmitted(updated_entry.id, target)],
      )
    }
  }
  let entry : Entry = {
    id: project_id_of(candidate_anchor),
    anchor: candidate_anchor,
    title,
    caption,
    added: now,
    opened: None,
  }
  let entries = ReadOnlyArray::from_array([..self.entries, entry])
  ({ entries, }, Added(entry, target), [ProjectAdmitted(entry.id, target)])
}

///|
/// Adds a plain folder at the end of the list with its default title and no
/// caption. Convenience wrapper around `admit`.
pub fn ProjectList::add(
  self : ProjectList,
  folder : FolderPath,
  now : @app.UnixMillis,
) -> (ProjectList, Entry, @app.Addition) {
  let located = Located::PlainFolder(ValidatedFolder::of_path(folder))
  let title = default_project_title(located.to_anchor())
  let (next, admission, _) = self.admit(located, title~, caption=None, now)
  match admission {
    Added(entry, _) => (next, entry, New)
    Existing(entry, _) => (next, entry, AlreadyListed)
  }
}

///|
/// Finds an entry by `ProjectId`, raising `UnknownProject` if absent.
pub fn ProjectList::entry(
  self : ProjectList,
  id : @app.ProjectId,
) -> Entry raise UnknownProject {
  match self.entries.iter().find_first(entry => entry.id == id) {
    Some(entry) => entry
    None => raise UnknownProject(id)
  }
}

///|
/// Replaces an existing entry with the same `id` (used after `reconcile`).
pub fn ProjectList::replace_entry(
  self : ProjectList,
  updated : Entry,
) -> ProjectList {
  let entries = self.entries.map(entry => {
    if entry.id == updated.id {
      updated
    } else {
      entry
    }
  })
  { entries, }
}

///|
/// Sets the time of the last open of a project, and gives its new entry. The
/// order of the list does not change.
pub fn ProjectList::open(
  self : ProjectList,
  id : @app.ProjectId,
  now : @app.UnixMillis,
) -> (ProjectList, Entry) raise UnknownProject {
  let opened = { ..self.entry(id), opened: Some(now), }
  let entries = self.entries.map(entry => {
    if entry.id == id {
      opened
    } else {
      entry
    }
  })
  ({ entries, }, opened)
}

///|
/// Atomically records `opened = Some(now)` on both the target workspace and its
/// owning project, returning the updated list, entry, workspace, and
/// `WorkspaceOpened` event.
pub fn ProjectList::open_workspace(
  self : ProjectList,
  project_id : @app.ProjectId,
  workspace_id : @app.WorkspaceId,
  observation : Observation,
  now : @app.UnixMillis,
) -> (ProjectList, Entry, DomainWorkspace, ReadOnlyArray[DomainEvent]) raise OpenWorkspaceError {
  let entry = self.entry(project_id) catch {
    UnknownProject(id) => raise OpenWorkspaceError::UnknownProject(id)
  }
  let (reconciled, workspaces, _) = entry.reconcile(observation)
  let found = match workspaces {
    Populated(set) => set.get(workspace_id)
    Empty | Unavailable(..) => None
  }
  guard found is Some(ws) else {
    raise OpenWorkspaceError::UnknownWorkspace(project_id, workspace_id)
  }
  let updated_anchor = match reconciled.anchor {
    Folder(path) => Anchor::Folder(path)
    Repository(backend~, store~, seen~) =>
      Anchor::Repository(
        backend~,
        store~,
        seen=seen.record_opened(ws.root, now),
      )
  }
  let updated_entry : Entry = {
    ..reconciled,
    anchor: updated_anchor,
    opened: Some(now),
  }
  let updated_ws : DomainWorkspace = { ..ws, opened: Some(now), }
  let next_list = self.replace_entry(updated_entry)
  (
    next_list,
    updated_entry,
    updated_ws,
    [WorkspaceOpened(project_id, workspace_id, now)],
  )
}

///|
/// Removes a project from the list, returning the remaining list, removed
/// entry, and `ProjectRemoved` event.
pub fn ProjectList::remove_with_events(
  self : ProjectList,
  id : @app.ProjectId,
) -> (ProjectList, Entry, ReadOnlyArray[DomainEvent]) raise UnknownProject {
  let removed = self.entry(id)
  (
    { entries: self.entries.filter(entry => entry.id != id), },
    removed,
    [ProjectRemoved(id)],
  )
}

///|
/// Removes a project from the list, and gives the entry that it had.
pub fn ProjectList::remove(
  self : ProjectList,
  id : @app.ProjectId,
) -> (ProjectList, Entry) raise UnknownProject {
  let (rest, removed, _) = self.remove_with_events(id)
  (rest, removed)
}

///|
/// The entries, in the order in which the user added them.
pub fn ProjectList::entries(self : ProjectList) -> ReadOnlyArray[Entry] {
  self.entries
}

///|
/// Finds the listed project whose plain folder or remembered checkout root is
/// the deepest ancestor of `current`, along with the matched `WorkspaceId` (if
/// any). Submodules registered as their own projects beat their enclosing
/// superproject because their checkout root is deeper.
pub fn ProjectList::project_of_folder(
  self : ProjectList,
  current : FolderPath,
) -> (Entry, @app.WorkspaceId?)? {
  let mut best : (Entry, FolderPath, @app.WorkspaceId?)? = None
  for entry in self.entries {
    match entry.anchor {
      Folder(path) =>
        if path.contains(current) {
          match best {
            Some((_, best_folder, _)) if !best_folder.contains(path) => ()
            _ => best = Some((entry, path, Some(workspace_id_of(path))))
          }
        }
      Repository(store~, seen~, ..) => {
        for item in seen.items() {
          if item.root.contains(current) {
            match best {
              Some((_, best_folder, _)) if !best_folder.contains(item.root) =>
                ()
              _ =>
                best = Some(
                  (entry, item.root, Some(workspace_id_of(item.root))),
                )
            }
          }
        }
        // Also match when the user is directly inside a bare repository store.
        if store.contains(current) && seen.items().is_empty() {
          match best {
            Some((_, best_folder, _)) if !best_folder.contains(store) => ()
            _ => best = Some((entry, store, None))
          }
        }
      }
    }
  }
  best.map(found => (found.0, found.2))
}

///|
fn same_title(
  platform : Platform,
  a : @app.ProjectTitle,
  b : @app.ProjectTitle,
) -> Bool {
  match platform {
    Windows => a.to_string().to_lower() == b.to_string().to_lower()
    MacOs | Linux => a.to_string() == b.to_string()
  }
}

///|
/// Explicit boundary projection from `ProjectList` to wire `@app.Project` DTOs
/// in the order of the list. `state_of` says whether the anchor of an entry
/// exists.
///
/// A project has a `parent` while another project shares the same display
/// title, by the case rule of the platform.
pub fn ProjectList::describe(
  self : ProjectList,
  state_of : (Entry) -> @app.FolderState,
) -> Array[@app.Project] {
  let projects = []
  for entry in self.entries {
    let display = entry.folder()
    let shared = self.entries
      .iter()
      .any(other => {
        other.id != entry.id &&
        same_title(display.platform(), other.title, entry.title)
      })
    let project : @app.Project = {
      id: entry.id,
      name: entry.name(),
      title: entry.title,
      caption: entry.caption,
      parent: if shared {
        display.parent_name()
      } else {
        None
      },
      path: display.to_string(),
      backend: entry.backend(),
      folder: state_of(entry),
      added: entry.added,
      opened: entry.opened,
    }
    projects.push(project)
  }
  projects
}

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

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

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

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

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

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