// Unified subprocess-based backend.
//
// All four supported OSes ship CLI utilities that read or write the
// system clipboard, so the per-OS difference is just the command name
// and argument list. `SubprocessBackend` captures that and delegates to
// `@async/process` for spawning.
//
// Failure handling translates `OSError::ENOENT` ("command not found")
// into `ClipboardError::ToolNotFound`, a `with_timeout_opt` miss into
// `ClipboardError::Timeout`, and any other process failure into
// `ClipboardError::Backend`.

///|
/// Default timeout (ms) for any single subprocess call. CLI clipboard
/// tools should be near-instant; if they take longer than this we treat
/// it as a hung tool. Tests may override via the `timeout_ms` field.
let default_timeout_ms : Int = 5000

///|
priv struct SubprocessBackend {
  get_cmd : String
  get_args : Array[String]
  set_cmd : String
  set_args : Array[String]
  // Whether the `set_cmd` self-forks into a long-lived selection owner
  // (xclip / wl-copy do this automatically once they've grabbed the
  // selection). When true, we route the child's stdout/stderr to
  // /dev/null so that detached owner doesn't keep the test runner's
  // stdio pipe alive after the parent process exits.
  daemonizes : Bool
  // Substrings that, when paired with a non-zero exit, indicate "no
  // clipboard content" (raised as `Empty`) rather than a real failure
  // (raised as `Backend`). For xclip the marker is "not available",
  // for wl-paste it's "No selection"; pbpaste / PowerShell signal
  // empty with exit 0 + empty stdout, so they use an empty list.
  empty_stderr_markers : Array[String]
  // Per-call timeout. Initialised to `default_timeout_ms` by the
  // dispatcher; white-box tests use a shorter value to exercise the
  // `Timeout` branch quickly.
  timeout_ms : Int
}

///|
/// Translate a low-level `@process` failure into our typed error.
fn map_process_error(cmd : String, err : Error) -> ClipboardError {
  match err {
    @os_error.OSError(_, ..) as e =>
      if e.is_ENOENT() {
        ToolNotFound(cmd)
      } else {
        Backend("\{cmd} failed: \{e}")
      }
    _ => Backend("\{cmd} failed: \{err}")
  }
}

///|
impl Backend for SubprocessBackend with fn get_text(self) {
  // `with_timeout_opt` returns None on timeout so we can translate it
  // into the typed `Timeout` error rather than letting an opaque
  // cancellation bubble up.
  let result = @async.with_timeout_opt(self.timeout_ms, () => {
    @process.collect_output(self.get_cmd, self.get_args[:])
  }) catch {
    err => raise map_process_error(self.get_cmd, err)
  }
  let (status, stdout, stderr) = match result {
    Some(t) => t
    None => raise Timeout(self.get_cmd)
  }
  // Clipboard CLIs use non-zero exit for both "no matching MIME type /
  // empty clipboard" and real failures (X server gone, Wayland socket
  // missing, …). We tell them apart by matching the tool's stderr
  // against per-backend markers configured in dispatcher.mbt: a marker
  // hit becomes `Empty`, anything else becomes `Backend()` so
  // callers get something diagnosable.
  if status != 0 {
    let raw = try stderr.text() catch {
      _ => ""
    } noraise {
      s => s
    }
    let text = raw.trim()
    for marker in self.empty_stderr_markers {
      if text.contains(marker) {
        raise Empty
      }
    }
    let msg = if text == "" {
      "\{self.get_cmd} exited with status \{status}"
    } else {
      "\{self.get_cmd} exited with status \{status}: \{text}"
    }
    raise Backend(msg)
  }
  let bytes = stdout.binary()
  if bytes.length() == 0 {
    raise Empty
  }
  decode_utf8(bytes)
}

///|
impl Backend for SubprocessBackend with fn set_text(self, text) {
  let bytes = encode_utf8(text)
  // The exit status is produced inside a nested closure and consumed
  // after the surrounding `with_timeout` returns; we shuttle it out via
  // a Ref cell because MoonBit closures don't have a non-local return.
  let exit_status : Ref[Int] = { val: 0 }
  @async.with_timeout(
    self.timeout_ms,
    () => {
      @async.with_task_group(group => {
        let (child_stdin, parent_write) = @process.write_to_process()
        // The writer task runs concurrently with the spawned process —
        // payloads larger than the 64 KiB Linux pipe buffer would deadlock
        // if we tried to pre-fill the pipe synchronously before spawn.
        group.spawn_bg(() => {
          defer parent_write.close()
          parent_write.write(bytes)
        })
        if self.daemonizes {
          // xclip / wl-copy daemonise to keep owning the selection. Without
          // detaching stderr, the daemon inherits our pipe and the test
          // runner's stdio never sees EOF, hanging the process indefinitely.
          let dev_null_out = @process.redirect_to_file(
            "/dev/null",
            create_mode=@fs.OpenExisting,
          )
          let dev_null_err = @process.redirect_to_file(
            "/dev/null",
            create_mode=@fs.OpenExisting,
          )
          exit_status.val = @process.run(
            self.set_cmd,
            self.set_args[:],
            stdin=child_stdin,
            stdout=dev_null_out,
            stderr=dev_null_err,
          )
        } else {
          exit_status.val = @process.run(
            self.set_cmd,
            self.set_args[:],
            stdin=child_stdin,
          )
        }
      })
    },
    error=Timeout(self.set_cmd),
  ) catch {
    Timeout(c) => raise Timeout(c)
    err => raise map_process_error(self.set_cmd, err)
  }
  if exit_status.val != 0 {
    raise Backend("\{self.set_cmd} exited with status \{exit_status.val}")
  }
}