// Runtime OS detection and backend dispatch.
//
// We detect the host platform from environment variables (cheap) and
// fall back to `uname -s` (one subprocess) for the Unix family. The
// per-OS clipboard tool is then wired into a `SubprocessBackend`.

///|
priv enum Os {
  MacOS
  Windows
  LinuxX11
  LinuxWayland
}

///|
async fn probe_os() -> Os raise ClipboardError {
  // Wayland takes precedence over X11 on Linux: most modern desktops
  // run a Wayland compositor and reach X11 only via XWayland.
  if @env.get_env_var("WAYLAND_DISPLAY") is Some(s) && s != "" {
    return LinuxWayland
  }
  if @env.get_env_var("OS") is Some("Windows_NT") {
    return Windows
  }
  // Run `uname -s` to distinguish Darwin (macOS) from Linux. We bound
  // the call by `default_timeout_ms` so a hung or hostile `uname` on
  // PATH can't stall `Clipboard::new()` forever; the rest of the
  // library uses the same timeout policy for its tools.
  let result = @async.with_timeout_opt(default_timeout_ms, () => {
    @process.collect_output("uname", ["-s"])
  }) catch {
    err => raise map_process_error("uname", err)
  }
  let (status, out, _) = match result {
    Some(t) => t
    None => raise Timeout("uname")
  }
  if status != 0 {
    raise Backend("uname exited with status \{status}")
  }
  let kernel = (try out.text() catch {
    _ => raise Backend("uname produced non-UTF-8 output")
  } noraise {
    s => s
  }).trim()
  match kernel {
    "Darwin" => MacOS
    "Linux" =>
      // We require X11 to actually be available before claiming
      // LinuxX11, because xclip refuses to run without DISPLAY. A
      // Linux host with neither DISPLAY nor WAYLAND_DISPLAY (raw
      // headless server) is genuinely unsupported by clipboard-mbt.
      if @env.get_env_var("DISPLAY") is Some(d) && d != "" {
        LinuxX11
      } else {
        raise Unsupported(
          "Linux without DISPLAY or WAYLAND_DISPLAY (headless host)",
        )
      }
    other => raise Unsupported("unrecognised kernel: \{other}")
  }
}

///|
async fn new_for_current_os() -> &Backend raise ClipboardError {
  let os = probe_os()
  match os {
    MacOS =>
      // pbpaste signals "empty clipboard" with exit 0 + empty stdout,
      // so we never need to interpret stderr for the Empty path.
      SubprocessBackend::{
        get_cmd: "pbpaste",
        get_args: [],
        set_cmd: "pbcopy",
        set_args: [],
        daemonizes: false,
        empty_stderr_markers: [],
        timeout_ms: default_timeout_ms,
      }
    Windows =>
      // PowerShell `Set-Clipboard` (rather than `clip.exe`) round-trips
      // Unicode correctly. `clip.exe` interprets its stdin in the
      // active console code page, which mangles non-ASCII text in many
      // setups. Trade-off: PowerShell startup adds ~hundreds of ms.
      //
      // Get/set both pin Console.Input/OutputEncoding to UTF-8 so the
      // pipes we share with the subprocess use UTF-8 end-to-end. Bare
      // `Get-Clipboard` would also append a trailing CRLF via the default
      // formatter; `[Console]::Out.Write` on the `-Raw` payload avoids
      // that. The `[string]` cast turns the `$null` an empty clipboard
      // produces into "" so `GetBytes` doesn't throw. Like pbpaste, an
      // empty clipboard yields exit 0 + empty stdout, so no stderr
      // markers are needed for the Empty path.
      SubprocessBackend::{
        get_cmd: "powershell",
        get_args: [
          "-NoProfile", "-NonInteractive", "-Command", "[Console]::OutputEncoding=[Text.Encoding]::UTF8;[Console]::Out.Write([string](Get-Clipboard -Raw))",
        ],
        set_cmd: "powershell",
        set_args: [
          "-NoProfile", "-NonInteractive", "-Command", "[Console]::InputEncoding=[Text.Encoding]::UTF8;Set-Clipboard -Value ([Console]::In.ReadToEnd())",
        ],
        daemonizes: false,
        empty_stderr_markers: [],
        timeout_ms: default_timeout_ms,
      }
    LinuxX11 =>
      // `xclip` self-forks once it has grabbed the CLIPBOARD selection:
      // the parent reads stdin, requests the selection, then forks a
      // daemon child and exits 0. So `@process.run` returns when the
      // parent xclip exits — fast — and its status reflects whether
      // the initial grab succeeded (DISPLAY missing, X server gone,
      // etc. surface here). The daemon child keeps owning the selection
      // until the calling process exits; this means clipboard contents
      // are tied to the calling process's lifetime, which matches what
      // pyperclip / clipboardy / atotto-clipboard etc. do.
      //
      // stdout / stderr are redirected to /dev/null (see
      // `daemonizes: true` in `subprocess.mbt`) so the daemon child
      // doesn't keep our pipes alive after the parent exits.
      //
      // Empty / unowned CLIPBOARD selection: xclip exits 1 with stderr
      // "Error: target STRING not available" (or UTF8_STRING etc.).
      // Real failures (Can't open display, allocation errors, …) also
      // exit 1 but their stderr does not contain "not available", so
      // the substring match cleanly separates the two.
      SubprocessBackend::{
        get_cmd: "xclip",
        get_args: ["-selection", "clipboard", "-o"],
        set_cmd: "xclip",
        set_args: ["-selection", "clipboard"],
        daemonizes: true,
        empty_stderr_markers: ["not available"],
        timeout_ms: default_timeout_ms,
      }
    LinuxWayland =>
      // `wl-copy` has the same self-fork behaviour as xclip; same
      // trade-off applies (parent exit status is meaningful, clipboard
      // contents die with the calling process).
      //
      // Empty selection: wl-paste exits 1 with a stderr that varies by
      // version — "Nothing is copied" from wl-clipboard v2.2.0 (April
      // 2023, commit a3a55ec) onward, and "No selection" on older
      // builds still shipping in Ubuntu 22.04 etc. We match both so
      // either generation maps cleanly to `Empty`. Other failures
      // (compositor down, wlr_data_control unsupported, ...) also exit
      // 1 but their stderr matches neither and falls through to the
      // `Backend(stderr)` branch.
      SubprocessBackend::{
        get_cmd: "wl-paste",
        get_args: ["--no-newline", "-t", "text/plain;charset=utf-8"],
        set_cmd: "wl-copy",
        set_args: ["-t", "text/plain;charset=utf-8"],
        daemonizes: true,
        empty_stderr_markers: ["Nothing is copied", "No selection"],
        timeout_ms: default_timeout_ms,
      }
  }
}