///|
/// A remembered workspace checkout root and its optional last-opened timestamp.
/// Core business model type (carries no serialization traits).
#derive(Eq, Debug)
pub(all) struct SeenWorkspace {
  root : FolderPath
  opened : @app.UnixMillis?
}

///|
/// Raised when constructing a `SeenWorkspaces` set with duplicate roots.
#derive(Eq, Debug)
pub(all) suberror SeenWorkspacesError {
  DuplicateRoot(FolderPath)
}

///|
/// Immutable deduplicated collection of remembered checkout roots for a
/// repository project.
#derive(Eq, Debug)
struct SeenWorkspaces {
  items : ReadOnlyArray[SeenWorkspace]
}

///|
/// An empty set of remembered workspaces.
pub fn SeenWorkspaces::empty() -> SeenWorkspaces {
  { items: [], }
}

///|
/// Constructs a validated deduplicated `SeenWorkspaces` collection.
pub fn SeenWorkspaces::SeenWorkspaces(
  items : ArrayView[SeenWorkspace],
) -> SeenWorkspaces raise SeenWorkspacesError {
  let kept : Array[SeenWorkspace] = []
  for item in items {
    if kept.iter().any(other => other.root.same_folder(item.root)) {
      raise DuplicateRoot(item.root)
    }
    kept.push(item)
  }
  { items: ReadOnlyArray::from_array(kept), }
}

///|
/// The remembered workspaces in order.
pub fn SeenWorkspaces::items(
  self : SeenWorkspaces,
) -> ReadOnlyArray[SeenWorkspace] {
  self.items
}

///|
/// Looks up a remembered workspace by canonical folder path.
pub fn SeenWorkspaces::find_root(
  self : SeenWorkspaces,
  root : FolderPath,
) -> SeenWorkspace? {
  self.items.iter().find_first(item => item.root.same_folder(root))
}

///|
/// Looks up a remembered workspace by derived `WorkspaceId`.
pub fn SeenWorkspaces::find_id(
  self : SeenWorkspaces,
  id : @app.WorkspaceId,
) -> SeenWorkspace? {
  self.items.iter().find_first(item => workspace_id_of(item.root) == id)
}

///|
/// Adds `root` to the remembered set if not already present, preserving any
/// existing `opened` timestamp.
pub fn SeenWorkspaces::remember(
  self : SeenWorkspaces,
  root : FolderPath,
) -> SeenWorkspaces {
  if self.find_root(root) is Some(_) {
    self
  } else {
    {
      items: ReadOnlyArray::from_array([..self.items, { root, opened: None, }]),
    }
  }
}

///|
/// Records `opened = Some(now)` for `root`, adding `root` if not already
/// remembered.
pub fn SeenWorkspaces::record_opened(
  self : SeenWorkspaces,
  root : FolderPath,
  now : @app.UnixMillis,
) -> SeenWorkspaces {
  let mut found = false
  let next : Array[SeenWorkspace] = []
  for item in self.items {
    if item.root.same_folder(root) {
      found = true
      next.push({ root: item.root, opened: Some(now), })
    } else {
      next.push(item)
    }
  }
  if !found {
    next.push({ root, opened: Some(now), })
  }
  { items: ReadOnlyArray::from_array(next), }
}

///|
/// What anchors a project in Mission Control: either one plain folder (always
/// exactly one workspace) or a VCS repository store (zero or more peer
/// workspaces).
#derive(Eq, Debug)
pub(all) enum Anchor {
  /// Plain folder: always exactly one workspace (the folder itself).
  Folder(FolderPath)
  /// Repository store (for example, Git common dir) with remembered checkout roots.
  Repository(
    backend~ : @app.BackendId,
    store~ : FolderPath,
    seen~ : SeenWorkspaces,
  )
}

///|
/// The VCS backend identifier of the anchor (`folder` for plain folders).
pub fn Anchor::backend(self : Anchor) -> @app.BackendId {
  match self {
    Folder(_) => @app.BackendId::folder()
    Repository(backend~, ..) => backend
  }
}

///|
/// Human-readable repository or folder name derived from the anchor.
/// For a normal Git `.git` directory, uses the enclosing checkout folder name.
/// For a bare `*.git` directory, strips the trailing `.git` suffix.
pub fn Anchor::name(self : Anchor) -> String {
  match self {
    Folder(path) => path.name()
    Repository(store~, ..) => {
      let base = store.name()
      if base == ".git" {
        match store.parent_name() {
          Some(parent) => parent
          None => base
        }
      } else if base.strip_suffix(".git") is Some(stem) && stem.length() > 0 {
        stem.to_owned()
      } else {
        base
      }
    }
  }
}

///|
/// Primary folder path displayed for the project (plain folder, enclosing repo
/// root for `.git`, first remembered checkout, or the bare store path).
pub fn Anchor::display_folder(self : Anchor) -> FolderPath {
  match self {
    Folder(path) => path
    Repository(store~, seen~, ..) =>
      if store.name() == ".git" && store.parent() is Some(parent) {
        parent
      } else if seen.items().get(0) is Some(first) {
        first.root
      } else {
        store
      }
  }
}

///|
/// The folder that the server checks to determine `Project.folder` state.
pub fn Anchor::check_folder(self : Anchor) -> FolderPath {
  match self {
    Folder(path) => path
    Repository(store~, ..) => store
  }
}

///|
/// True when two anchors refer to the same plain folder or the same backend
/// repository store.
pub fn Anchor::same_anchor(self : Anchor, other : Anchor) -> Bool {
  match (self, other) {
    (Folder(a), Folder(b)) => a.same_folder(b)
    (Repository(backend=ba, store=sa, ..), Repository(backend=bb, store=sb, ..)) =>
      ba == bb && sa.same_folder(sb)
    _ => false
  }
}

///|
/// Core business model representation of one peer workspace (zero serialization
/// traits; uses canonical `FolderPath`).
#derive(Eq, Debug)
pub(all) struct DomainWorkspace {
  id : @app.WorkspaceId
  name : @app.WorkspaceName
  root : FolderPath
  backend : @app.BackendId
  folder : @app.FolderState
  position : @app.Position
  opened : @app.UnixMillis?
}

///|
/// Explicit boundary projection from core `DomainWorkspace` to wire
/// `@app.Workspace`.
pub fn DomainWorkspace::to_wire(self : DomainWorkspace) -> @app.Workspace {
  {
    id: self.id,
    name: self.name,
    path: self.root.to_string(),
    backend: self.backend,
    folder: self.folder,
    position: self.position,
    opened: self.opened,
  }
}

///|
/// Core non-empty set of peer workspaces guaranteeing unique IDs and that
/// `default_id` is a member (zero serialization traits).
#derive(Eq, Debug)
struct DomainWorkspaceSet {
  workspaces : ReadOnlyArray[DomainWorkspace]
  default_id : @app.WorkspaceId
}

///|
/// Constructs a validated non-empty `DomainWorkspaceSet`.
pub fn DomainWorkspaceSet::DomainWorkspaceSet(
  workspaces : ArrayView[DomainWorkspace],
  default_id~ : @app.WorkspaceId,
) -> DomainWorkspaceSet raise @app.WorkspaceSetError {
  guard !workspaces.is_empty() else { raise NoWorkspace }
  let seen : Map[@app.WorkspaceId, Unit] = Map([])
  let mut has_default = false
  for ws in workspaces {
    if seen.contains(ws.id) {
      raise DuplicateWorkspace(ws.id)
    }
    seen[ws.id] = ()
    if ws.id == default_id {
      has_default = true
    }
  }
  guard has_default else { raise DefaultNotMember(default_id) }
  { workspaces: ReadOnlyArray::from_iter(workspaces.iter()), default_id, }
}

///|
/// The immutable list of peer workspaces in display order.
pub fn DomainWorkspaceSet::workspaces(
  self : DomainWorkspaceSet,
) -> ReadOnlyArray[DomainWorkspace] {
  self.workspaces
}

///|
/// The guaranteed-member default workspace ID.
pub fn DomainWorkspaceSet::default_id(
  self : DomainWorkspaceSet,
) -> @app.WorkspaceId {
  self.default_id
}

///|
/// Looks up a workspace by its ID.
pub fn DomainWorkspaceSet::get(
  self : DomainWorkspaceSet,
  id : @app.WorkspaceId,
) -> DomainWorkspace? {
  self.workspaces.iter().find_first(ws => ws.id == id)
}

///|
/// Returns the default workspace (total by smart-constructor invariant).
pub fn DomainWorkspaceSet::default_workspace(
  self : DomainWorkspaceSet,
) -> DomainWorkspace {
  match self.get(self.default_id) {
    Some(ws) => ws
    None => self.workspaces[0]
  }
}

///|
/// Explicit boundary projection to wire `@app.WorkspaceSet`.
pub fn DomainWorkspaceSet::to_wire(
  self : DomainWorkspaceSet,
) -> @app.WorkspaceSet {
  let wire = self.workspaces.iter().map(ws => ws.to_wire()).collect()
  @app.WorkspaceSet::WorkspaceSet(wire, default_id=self.default_id) catch {
    _ => abort("valid DomainWorkspaceSet failed to project to wire")
  }
}

///|
/// Core business representation of a project's workspace state.
#derive(Eq, Debug)
pub(all) enum DomainProjectWorkspaces {
  Empty
  Populated(DomainWorkspaceSet)
  Unavailable(
    reason~ : @app.UnavailableReason,
    remembered~ : ReadOnlyArray[SeenWorkspace],
  )
}

///|
/// Explicit boundary projection to wire `@app.ProjectWorkspaces`.
pub fn DomainProjectWorkspaces::to_wire(
  self : DomainProjectWorkspaces,
) -> @app.ProjectWorkspaces {
  match self {
    Empty => Empty
    Populated(set) => Populated(set.to_wire())
    Unavailable(reason~, remembered~) =>
      Unavailable(
        reason~,
        remembered=ReadOnlyArray::from_iter(
          remembered
          .iter()
          .map(item => {
            id: workspace_id_of(item.root),
            name: default_workspace_name(item.root),
            path: item.root.to_string(),
            opened: item.opened,
          }),
        ),
      )
  }
}

///|
/// Explicit domain events returned by pure core workflows for the imperative
/// shell to act on.
#derive(Eq, Debug)
pub(all) enum DomainEvent {
  ProjectAdmitted(@app.ProjectId, @app.AddedTarget)
  ProjectRemoved(@app.ProjectId)
  WorkspaceOpened(@app.ProjectId, @app.WorkspaceId, @app.UnixMillis)
  WorkspacesReconciled(@app.ProjectId, DomainProjectWorkspaces)
}

///|
/// Typestate step 1: raw untrusted path string entering the domain boundary.
#derive(Eq, Debug)
pub(all) struct UnvalidatedFolderPath {
  raw : String
}

///|
/// Typestate step 2: validated canonical absolute folder path.
#derive(Eq, Debug)
struct ValidatedFolder {
  path : FolderPath
}

///|
/// Validates a raw folder path string for `platform`.
pub fn UnvalidatedFolderPath::validate(
  self : UnvalidatedFolderPath,
  platform : Platform,
) -> ValidatedFolder raise FolderPathError {
  { path: FolderPath::FolderPath(self.raw, platform), }
}

///|
/// Wraps an already-validated `FolderPath` as a `ValidatedFolder`.
pub fn ValidatedFolder::of_path(path : FolderPath) -> ValidatedFolder {
  { path, }
}

///|
/// Extracts the canonical `FolderPath`.
pub fn ValidatedFolder::path(self : ValidatedFolder) -> FolderPath {
  self.path
}

///|
/// Typestate step 3: classification of a validated folder by VCS backends.
#derive(Eq, Debug)
pub(all) enum Located {
  PlainFolder(ValidatedFolder)
  Checkout(backend~ : @app.BackendId, store~ : FolderPath, root~ : FolderPath)
  BareStore(backend~ : @app.BackendId, store~ : FolderPath)
}

///|
/// Derives the initial `Anchor` corresponding to a `Located` classification.
pub fn Located::to_anchor(self : Located) -> Anchor {
  match self {
    PlainFolder(folder) => Folder(folder.path())
    Checkout(backend~, store~, root~) =>
      Repository(backend~, store~, seen=SeenWorkspaces::empty().remember(root))
    BareStore(backend~, store~) =>
      Repository(backend~, store~, seen=SeenWorkspaces::empty())
  }
}

///|
/// Typestate step 4: result of admitting a `Located` target into `ProjectList`.
#derive(Eq, Debug)
pub(all) enum Admission {
  Added(Entry, @app.AddedTarget)
  Existing(Entry, @app.AddedTarget)
}

///|
/// One observed working tree returned by a VCS backend.
#derive(Eq, Debug)
pub(all) struct Checkout {
  root : FolderPath
  folder : @app.FolderState
  position : @app.Position
}

///|
/// Outcome of observing a project's workspaces through its VCS backend.
#derive(Eq, Debug)
pub(all) enum Observation {
  Checkouts(ReadOnlyArray[Checkout])
  NoAnswer(@app.UnavailableReason)
}

///|
/// Raised when opening a workspace fails in the pure domain core.
#derive(Eq, Debug)
pub(all) suberror OpenWorkspaceError {
  UnknownProject(@app.ProjectId)
  UnknownWorkspace(@app.ProjectId, @app.WorkspaceId)
}

///|
/// Derives the deterministic default workspace ID from a non-empty list:
/// the `Present` workspace with the latest `opened` timestamp (with ties broken
/// in favor of the later workspace in the list, matching `Entry::last_opened`),
/// else the first `Present` workspace, else the first workspace in the list.
fn derive_default_workspace_id(
  workspaces : ReadOnlyArray[DomainWorkspace],
) -> @app.WorkspaceId {
  let mut best_opened : (@app.WorkspaceId, Int64)? = None
  let mut first_present : @app.WorkspaceId? = None
  for ws in workspaces {
    if ws.folder == Present {
      if first_present is None {
        first_present = Some(ws.id)
      }
      if ws.opened is Some(opened) {
        let t = opened.to_int64()
        match best_opened {
          Some((_, latest)) if t < latest => ()
          _ => best_opened = Some((ws.id, t))
        }
      }
    }
  }
  match best_opened {
    Some((id, _)) => id
    None =>
      match first_present {
        Some(id) => id
        None => workspaces[0].id
      }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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