///|
/// Single async I/O boundary answering pure `@core.Inquiry[T]` decision trees.
pub(open) trait Machine {
  async fn run(Self, @core.ToolCall) -> @core.ToolAnswer noraise
  async fn look(Self, @core.FolderPath) -> @core.Looked noraise
  async fn names(Self, @core.FolderPath) -> @core.Listing noraise
  async fn read_file(Self, @core.FolderPath) -> @core.FileText noraise
  async fn real_path(Self, @core.FolderPath) -> @core.RealPathAnswer noraise
}

///|
/// Executes a pure `@core.Inquiry[T]` decision tree against a `Machine`.
pub async fn[T] answer(
  inquiry : @core.Inquiry[T],
  machine : &Machine,
) -> T noraise {
  let mut step = inquiry
  while true {
    match step {
      Done(value) => return value
      Run(call, resume_fn) => step = resume_fn(machine.run(call))
      Look(path, resume_fn) => step = resume_fn(machine.look(path))
      Names(path, resume_fn) => step = resume_fn(machine.names(path))
      ReadFile(path, resume_fn) => step = resume_fn(machine.read_file(path))
      RealPath(path, resume_fn) => step = resume_fn(machine.real_path(path))
    }
  }
  panic()
}

///|
/// Raised when constructing a `MachineTimeout` with a zero duration.
#derive(Eq, Debug)
pub(all) suberror MachineTimeoutError {
  ZeroTimeout
}

///|
/// A validated positive per-call timeout (1 to 65535 milliseconds) for
/// `RealMachine` subprocess and filesystem operations.
#derive(Eq, Debug)
struct MachineTimeout {
  duration : Duration
}

///|
/// Constructs a positive `MachineTimeout` in milliseconds (1 to 65535).
pub fn MachineTimeout::MachineTimeout(
  millis : UInt16,
) -> MachineTimeout raise MachineTimeoutError {
  guard millis > 0 else { raise ZeroTimeout }
  { duration: Duration(millis), }
}

///|
/// The default `MachineTimeout` (5000 milliseconds).
pub fn MachineTimeout::default() -> MachineTimeout {
  { duration: Duration(5000), }
}

///|
/// The timeout in milliseconds.
pub fn MachineTimeout::millis(self : MachineTimeout) -> Int32 {
  self.duration.millis()
}

///|
/// Allowed external tool names that `RealMachine::run` may execute.
let allowed_tools : ReadOnlyArray[@core.ToolName] = [@core.ToolName::git()]

///|
let max_machine_file_bytes : Int64 = 1_048_576L

///|
/// Production `Machine` implementation enforcing an allow-list of tools,
/// positive bounded timeouts, 1 MiB file reads, and detached filesystem probes
/// so hung network shares or slow subprocesses cannot stall calls.
pub struct RealMachine {
  priv spawn : (async () -> Unit) -> Unit
  priv timeout : MachineTimeout
  priv read_kind : async (@core.FolderPath) -> @core.Looked noraise
  priv read_names : async (@core.FolderPath) -> @core.Listing noraise
  priv read_text : async (@core.FolderPath) -> @core.FileText noraise
  priv resolve_real : async (@core.FolderPath) -> @core.RealPathAnswer noraise
}

///|
/// Constructs a `RealMachine` running filesystem probes in `reads` with a
/// validated positive per-call `timeout` (default 5000 ms).
pub fn[X] RealMachine::RealMachine(
  reads : @async.TaskGroup[X],
  timeout~ : MachineTimeout = MachineTimeout::default(),
) -> RealMachine {
  {
    spawn: run => reads.spawn_bg(run, no_wait=true),
    timeout,
    read_kind: look_path,
    read_names: list_path,
    read_text: read_text_path,
    resolve_real: real_path_answer,
  }
}

///|
async fn read_text_path(path : @core.FolderPath) -> @core.FileText noraise {
  try {
    let file = @fs.open(path.to_string(), mode=ReadOnly)
    defer file.close()
    guard file.kind() is Regular else {
      return Failed("path is not a regular file")
    }
    if file.size() > max_machine_file_bytes {
      return TooLarge
    }
    let chunks : Array[Bytes] = []
    let mut total : Int64 = 0L
    while true {
      match file.read_some(max_len=16384) {
        None => break
        Some(chunk) => {
          total += chunk.length().to_int64()
          if total > max_machine_file_bytes {
            return TooLarge
          }
          chunks.push(chunk)
        }
      }
    }
    let out = FixedArray::make(total.to_int(), b'\x00')
    let mut offset = 0
    for chunk in chunks {
      for i in 0.. Missing
    error => Failed(reason_of(error))
  }
}

///|
async fn real_path_answer(
  path : @core.FolderPath,
) -> @core.RealPathAnswer noraise {
  try real_path(path) catch {
    error if is_missing(error) => Missing
    error => Failed(reason_of(error))
  } noraise {
    resolved => Resolved(resolved)
  }
}

///|
async fn look_path(path : @core.FolderPath) -> @core.Looked noraise {
  try @fs.kind(path.to_string()) catch {
    @os_error.OSError(_) as err if err.is_ENOENT() => Missing
    @os_error.OSError(_) as err if err.is_EACCES() => Folder
    err => Failed(reason_of(err))
  } noraise {
    Directory => Folder
    Regular => File
    _ => Missing
  }
}

///|
async fn list_path(path : @core.FolderPath) -> @core.Listing noraise {
  try @fs.readdir(path.to_string()) catch {
    @os_error.OSError(_) as err if err.is_ENOENT() => Missing
    err => Failed(reason_of(err))
  } noraise {
    entries => Entries(ReadOnlyArray::from_array(entries))
  }
}

///|
async fn[T] run_detached(
  spawn : (async () -> Unit) -> Unit,
  timeout : MachineTimeout,
  work : async () -> T noraise,
  on_timeout : T,
) -> T noraise {
  let result : Ref[T?] = Ref(None)
  let ended = Ref(false)
  let end = @cond_var.Cond()
  spawn(() => {
    defer {
      ended.val = true
      end.broadcast()
    }
    result.val = Some(work())
  })
  try
    @async.with_timeout_opt(timeout.millis(), () => {
      while !ended.val {
        end.wait()
      }
    })
    |> ignore
  catch {
    _ => ()
  }
  match result.val {
    Some(value) => value
    None => on_timeout
  }
}

///|
pub impl Machine for RealMachine with fn run(self, call) {
  guard allowed_tools.contains(call.program) else {
    return Failed("tool \"\{call.program}\" is not in the allowed tool list")
  }
  let res = @async.with_timeout_opt(self.timeout.millis(), () => {
    @process.collect_output(
      call.program.to_string(),
      call.args.iter().collect(),
      cwd=call.cwd.to_string(),
    )
  }) catch {
    @os_error.OSError(_) as err if err.is_ENOENT() =>
      return @core.ToolAnswer::NotInstalled
    err => return @core.ToolAnswer::Failed(reason_of(err))
  }
  match res {
    None => TimedOut
    Some((code, out_data, err_data)) => {
      let stdout = @utf8.decode_lossy(out_data.binary()[:])
      let stderr = @utf8.decode_lossy(err_data.binary()[:])
      Exited(code~, stdout~, stderr~)
    }
  }
}

///|
pub impl Machine for RealMachine with fn look(self, path) {
  run_detached(self.spawn, self.timeout, () => (self.read_kind)(path), TimedOut)
}

///|
pub impl Machine for RealMachine with fn names(self, path) {
  run_detached(
    self.spawn,
    self.timeout,
    () => (self.read_names)(path),
    Failed("listing timed out"),
  )
}

///|
pub impl Machine for RealMachine with fn read_file(self, path) {
  run_detached(self.spawn, self.timeout, () => (self.read_text)(path), TimedOut)
}

///|
pub impl Machine for RealMachine with fn real_path(self, path) {
  run_detached(
    self.spawn,
    self.timeout,
    () => (self.resolve_real)(path),
    TimedOut,
  )
}

///|
/// Deterministic in-memory `Machine` implementation for acceptance and unit
/// tests running the real `GitBackend`, `GitMetadataDeriver`, source adapters,
/// mount providers, and `ProjectList`.
pub struct FakeMachine {
  priv on_run : (@core.ToolCall) -> @core.ToolAnswer
  priv on_look : (@core.FolderPath) -> @core.Looked
  priv on_names : (@core.FolderPath) -> @core.Listing
  priv on_read_file : (@core.FolderPath) -> @core.FileText
  priv on_real_path : (@core.FolderPath) -> @core.RealPathAnswer
}

///|
/// Constructs a `FakeMachine` from scripted handlers.
pub fn FakeMachine::FakeMachine(
  on_run~ : (@core.ToolCall) -> @core.ToolAnswer = _ => NotInstalled,
  on_look~ : (@core.FolderPath) -> @core.Looked = _ => Folder,
  on_names~ : (@core.FolderPath) -> @core.Listing = _ => Entries([]),
  on_read_file~ : (@core.FolderPath) -> @core.FileText = _ => Missing,
  on_real_path~ : (@core.FolderPath) -> @core.RealPathAnswer = p => Resolved(p),
) -> FakeMachine {
  { on_run, on_look, on_names, on_read_file, on_real_path, }
}

///|
pub impl Machine for FakeMachine with fn run(self, call) {
  (self.on_run)(call)
}

///|
pub impl Machine for FakeMachine with fn look(self, path) {
  (self.on_look)(path)
}

///|
pub impl Machine for FakeMachine with fn names(self, path) {
  (self.on_names)(path)
}

///|
pub impl Machine for FakeMachine with fn read_file(self, path) {
  (self.on_read_file)(path)
}

///|
pub impl Machine for FakeMachine with fn real_path(self, path) {
  (self.on_real_path)(path)
}

///|
/// Answers a pure `@core.Inquiry[T]` synchronously using this `FakeMachine`'s
/// scripted handlers (useful inside synchronous Gherkin step definitions).
pub fn[T] FakeMachine::answer_sync(
  self : FakeMachine,
  inquiry : @core.Inquiry[T],
) -> T {
  let mut step = inquiry
  while true {
    match step {
      Done(value) => return value
      Run(call, resume_fn) => step = resume_fn((self.on_run)(call))
      Look(path, resume_fn) => step = resume_fn((self.on_look)(path))
      Names(path, resume_fn) => step = resume_fn((self.on_names)(path))
      ReadFile(path, resume_fn) => step = resume_fn((self.on_read_file)(path))
      RealPath(path, resume_fn) => step = resume_fn((self.on_real_path)(path))
    }
  }
  panic()
}

///|
/// Default built-in VCS backends (`GitBackend`).
pub fn default_backends() -> @core.Backends {
  @core.Backends::Backends([@git.GitBackend::GitBackend()]) catch {
    _ => @core.Backends::empty()
  }
}

///|
/// Default built-in metadata deriver chain (`GitMetadataDeriver`, then
/// `FolderPathDeriver`).
pub fn default_derivers() -> @core.MetadataDerivers {
  @core.MetadataDerivers::MetadataDerivers([
    @git.GitMetadataDeriver::GitMetadataDeriver() as &@core.MetadataDeriver,
    @core.FolderPathDeriver::{ } as &@core.MetadataDeriver,
  ])
}

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

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

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

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

///|
pub extend RealMachine with Machine::{run, look, names, read_file, real_path}

///|
pub extend FakeMachine with Machine::{run, look, names, read_file, real_path}