///|
/// A rule of an external tool executable name.
#derive(Eq, Debug)
pub(all) enum ToolNameRule {
  /// The text is empty.
  Empty
  /// The text contains whitespace or a control character.
  WhitespaceOrControl
  /// The text contains a path separator (`/` or `\`).
  PathSeparator
}

///|
/// Raised when a text is not a valid external tool name.
#derive(Eq, Debug)
pub(all) suberror ToolNameError {
  /// The text, and the first rule that it breaks.
  InvalidToolName(text~ : String, rule~ : ToolNameRule)
}

///|
/// A validated bare external executable name (no path separators, whitespace,
/// or control characters). `Machine` additionally enforces an allow-list.
#derive(Eq, Compare, Hash, Debug)
struct ToolName {
  text : String
}

///|
/// Parses a bare external tool executable name.
pub fn ToolName::ToolName(text : String) -> ToolName raise ToolNameError {
  guard !text.is_empty() else { raise InvalidToolName(text~, rule=Empty) }
  for c in text {
    let code = c.to_int()
    if code <= 0x20 || code == 0x7f {
      raise InvalidToolName(text~, rule=WhitespaceOrControl)
    }
    if c == '/' || c == '\\' {
      raise InvalidToolName(text~, rule=PathSeparator)
    }
  }
  { text, }
}

///|
/// The `git` executable name (total constructor).
pub fn ToolName::git() -> ToolName {
  { text: "git", }
}

///|
/// The bare tool executable name text.
pub fn ToolName::to_string(self : ToolName) -> String {
  self.text
}

///|
pub impl Show for ToolName with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
/// A command request issued by a pure `Inquiry[T]` decision tree.
#derive(Eq, Debug)
pub(all) struct ToolCall {
  /// The validated executable name (enforced against an allow-list by `Machine`).
  program : ToolName
  args : ReadOnlyArray[String]
  cwd : FolderPath
}

///|
/// The answer returned by `Machine::run` for a `ToolCall`.
#derive(Eq, Debug)
pub(all) enum ToolAnswer {
  Exited(code~ : Int32, stdout~ : String, stderr~ : String)
  NotInstalled
  TimedOut
  Failed(String)
}

///|
/// The answer returned by `Machine::look` for one folder path.
#derive(Eq, Debug)
pub(all) enum Looked {
  Folder
  File
  Missing
  TimedOut
  Failed(String)
}

///|
/// The answer returned by `Machine::names` for one directory listing.
#derive(Eq, Debug)
pub(all) enum Listing {
  Entries(ReadOnlyArray[String])
  Missing
  Failed(String)
}

///|
/// The answer returned by `Machine::read_file` for one text file read (capped at 1 MiB).
#derive(Eq, Debug)
pub(all) enum FileText {
  Found(String)
  Missing
  TooLarge
  TimedOut
  Failed(String)
}

///|
/// The answer returned by `Machine::real_path` for canonical symlink resolution.
#derive(Eq, Debug)
pub(all) enum RealPathAnswer {
  Resolved(FolderPath)
  Missing
  TimedOut
  Failed(String)
}

///|
/// Pure decision tree describing questions a VCS backend, metadata deriver,
/// source adapter, or mount provider asks the host machine, answered by `Machine`.
pub(all) enum Inquiry[T] {
  Done(T)
  Run(ToolCall, (ToolAnswer) -> Inquiry[T])
  Look(FolderPath, (Looked) -> Inquiry[T])
  Names(FolderPath, (Listing) -> Inquiry[T])
  ReadFile(FolderPath, (FileText) -> Inquiry[T])
  RealPath(FolderPath, (RealPathAnswer) -> Inquiry[T])
}

///|
/// Sequences another `Inquiry` step after the result of this `Inquiry`.
pub fn[T, U] Inquiry::then(
  self : Inquiry[T],
  next : (T) -> Inquiry[U],
) -> Inquiry[U] {
  match self {
    Done(value) => next(value)
    Run(call, resume_fn) => Run(call, answer => resume_fn(answer).then(next))
    Look(path, resume_fn) => Look(path, answer => resume_fn(answer).then(next))
    Names(path, resume_fn) =>
      Names(path, answer => resume_fn(answer).then(next))
    ReadFile(path, resume_fn) =>
      ReadFile(path, answer => resume_fn(answer).then(next))
    RealPath(path, resume_fn) =>
      RealPath(path, answer => resume_fn(answer).then(next))
  }
}

///|
/// Maps a pure function over the final value of an `Inquiry`.
pub fn[T, U] Inquiry::map(self : Inquiry[T], f : (T) -> U) -> Inquiry[U] {
  self.then(value => Done(f(value)))
}

///|
/// Open-closed extension point for VCS backends (such as Git or Jujutsu).
/// Backends are pure 4-target packages that return `Inquiry[T]` trees.
pub(open) trait VcsBackend {
  /// Stable open backend identifier (`git`, `jj`, etc.).
  fn id(Self) -> @app.BackendId
  /// Classifies `folder` for this backend, or returns `None` if it does not belong.
  fn locate(Self, FolderPath) -> Inquiry[Located?]
  /// Observes all working trees anchored at `store`.
  fn observe(Self, FolderPath) -> Inquiry[Observation]
}

///|
/// Raised when constructing a `Backends` registry with duplicate backend IDs.
#derive(Eq, Debug)
pub(all) suberror DuplicateBackend {
  DuplicateBackend(@app.BackendId)
}

///|
/// Priority-ordered registry of VCS backends; plain folder is the total fallback.
struct Backends {
  list : ReadOnlyArray[&VcsBackend]
}

///|
/// Constructs a validated `Backends` registry with unique backend IDs.
pub fn Backends::Backends(
  list : ArrayView[&VcsBackend],
) -> Backends raise DuplicateBackend {
  let seen : Map[@app.BackendId, Unit] = Map([])
  for backend in list {
    let id = backend.id()
    if seen.contains(id) {
      raise DuplicateBackend(id)
    }
    seen[id] = ()
  }
  { list: ReadOnlyArray::from_iter(list.iter()), }
}

///|
/// An empty registry containing no VCS backends (every folder classifies as
/// `PlainFolder`).
pub fn Backends::empty() -> Backends {
  { list: [], }
}

///|
/// Classifies a validated folder by querying registered backends in priority
/// order, falling back to `Located::PlainFolder`.
pub fn Backends::locate(
  self : Backends,
  folder : ValidatedFolder,
) -> Inquiry[Located] {
  fn step(index : Int32) -> Inquiry[Located] {
    match self.list.get(index) {
      None => Done(PlainFolder(folder))
      Some(backend) =>
        backend
        .locate(folder.path())
        .then(found => {
          match found {
            Some(located) => Done(located)
            None => step(index + 1)
          }
        })
    }
  }
  step(0)
}

///|
/// Observes all peer workspaces for a project `Anchor`.
pub fn Backends::observe(
  self : Backends,
  anchor : Anchor,
) -> Inquiry[Observation] {
  match anchor {
    Folder(path) =>
      Look(path, looked => {
        let folder : @app.FolderState = match looked {
          Folder => Present
          File | Missing | TimedOut | Failed(_) => Missing
        }
        Done(Checkouts([{ root: path, folder, position: Unversioned, }]))
      })
    Repository(backend~, store~, ..) =>
      match self.list.iter().find_first(item => item.id() == backend) {
        None => Done(NoAnswer(BackendNotKnown(backend)))
        Some(driver) =>
          Look(store, looked => {
            match looked {
              Folder | File => driver.observe(store)
              Missing => Done(NoAnswer(StoreMissing))
              TimedOut => Done(NoAnswer(TimedOut))
              Failed(msg) => Done(NoAnswer(Failed(msg)))
            }
          })
      }
  }
}

///|
/// Partial project metadata contributed by one `MetadataDeriver`.
/// Forms a left-biased monoid under `DerivedMetadata::empty` and `or_else`.
#derive(Eq, Debug)
pub(all) struct DerivedMetadata {
  title : @app.ProjectTitle?
  caption : @app.ProjectCaption?
}

///|
/// Empty partial metadata (identity element for `or_else`).
pub fn DerivedMetadata::empty() -> DerivedMetadata {
  { title: None, caption: None, }
}

///|
/// Left-biased merge: keeps `self`'s fields when present, falling back to
/// `fallback` for omitted fields.
pub fn DerivedMetadata::or_else(
  self : DerivedMetadata,
  fallback : DerivedMetadata,
) -> DerivedMetadata {
  {
    title: match self.title {
      Some(_) => self.title
      None => fallback.title
    },
    caption: match self.caption {
      Some(_) => self.caption
      None => fallback.caption
    },
  }
}

///|
/// Open-closed strategy for deriving default project title and caption from a
/// located anchor (and optionally VCS/file details via `Inquiry`).
pub(open) trait MetadataDeriver {
  fn infer(Self, Located) -> Inquiry[DerivedMetadata]
}

///|
/// Functional adapter wrapping a plain lambda as a `MetadataDeriver`.
pub(all) struct FnMetadataDeriver((Located) -> Inquiry[DerivedMetadata])

///|
pub impl MetadataDeriver for FnMetadataDeriver with fn infer(self, located) {
  (self.0)(located)
}

///|
/// Built-in pure deriver that supplies the default title from the anchor's
/// folder or bare-repository name.
pub(all) struct FolderPathDeriver {}

///|
pub impl MetadataDeriver for FolderPathDeriver with fn infer(_, located) {
  Done({
    title: Some(default_project_title(located.to_anchor())),
    caption: None,
  })
}

///|
/// Ordered chain of metadata derivers that merges explicit user overrides
/// first, then derivers in priority order, with a total fallback to
/// `default_project_title`.
struct MetadataDerivers {
  list : ReadOnlyArray[&MetadataDeriver]
}

///|
/// Constructs a `MetadataDerivers` chain.
pub fn MetadataDerivers::MetadataDerivers(
  list : ArrayView[&MetadataDeriver],
) -> MetadataDerivers {
  { list: ReadOnlyArray::from_iter(list.iter()), }
}

///|
/// Default chain containing only `FolderPathDeriver`.
pub fn MetadataDerivers::folder_only() -> MetadataDerivers {
  MetadataDerivers([FolderPathDeriver::{ } as &MetadataDeriver])
}

///|
/// Resolves final `(ProjectTitle, ProjectCaption?)`, applying `explicit` user
/// overrides first, then derivers in priority order (short-circuiting once both
/// fields are populated), then falling back to `default_project_title`.
pub fn MetadataDerivers::resolve(
  self : MetadataDerivers,
  located : Located,
  explicit~ : DerivedMetadata,
) -> Inquiry[(@app.ProjectTitle, @app.ProjectCaption?)] {
  fn step(
    index : Int32,
    acc : DerivedMetadata,
  ) -> Inquiry[(@app.ProjectTitle, @app.ProjectCaption?)] {
    if acc.title is Some(title) && acc.caption is Some(_) {
      return Done((title, acc.caption))
    }
    match self.list.get(index) {
      None => {
        let title = match acc.title {
          Some(t) => t
          None => default_project_title(located.to_anchor())
        }
        Done((title, acc.caption))
      }
      Some(deriver) =>
        deriver.infer(located).then(next => step(index + 1, acc.or_else(next)))
    }
  }
  step(0, explicit)
}

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

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

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

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

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

///|
pub extend ToolName with Compare::{op_lt, op_le, op_ge, compare, op_gt}

///|
pub extend ToolName with Hash::{hash, hash_combine}

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

///|
pub extend ToolName with Show::{output}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

///|
pub extend FnMetadataDeriver with MetadataDeriver::{infer}

///|
pub extend FolderPathDeriver with MetadataDeriver::{infer}