// sarah-name: Clipboard Bridge
// sarah-version: 1.0.0
// sarah-description: Read and write the system clipboard (X11/Wayland, may be headless).
// sarah-category: Files & System

manifest = {
  name: "Clipboard Bridge",
  version: "1.0.0",
  description: "System clipboard read/write bridge",
  commands: [
    { id: "read", title: "Read clipboard", tool: "clip_read" },
    { id: "write", title: "Write clipboard", tool: "clip_write" }
  ]
};

tools = [
  {
    name: "clip_read",
    description: "Read system clipboard text (xclip, xsel, wl-paste chain)",
    parameters: { type: "object", properties: {} },
    run: async (args, sarah) => {
      const cmds = [
        "xclip -selection clipboard -o 2>/dev/null",
        "xsel --clipboard --output 2>/dev/null",
        "wl-paste 2>/dev/null"
      ];
      for (const c of cmds) {
        const r = await sarah.shell.run(c);
        if (r.code === 0 && r.stdout) return r.stdout.slice(0, 4000);
      }
      return "Clipboard unavailable (headless server?). Install one: sudo apt install xclip | xsel | wl-clipboard. A desktop session is required.";
    }
  },
  {
    name: "clip_write",
    description: "Write text to the system clipboard",
    parameters: {
      type: "object",
      properties: { text: { type: "string", description: "Text to copy" } },
      required: ["text"]
    },
    run: async (args, sarah) => {
      const text = String(args.text || "");
      if (!text) throw new Error("Nothing to copy: text is empty");
      const b64 = JSON.stringify(text);
      void b64;
      const safe = text.replace(/'/g, "'\\''");
      const tries = [
        "printf '%s' '" + safe + "' | xclip -selection clipboard 2>/dev/null",
        "printf '%s' '" + safe + "' | xsel --clipboard --input 2>/dev/null",
        "printf '%s' '" + safe + "' | wl-copy 2>/dev/null"
      ];
      for (const c of tries) {
        const r = await sarah.shell.run(c);
        if (r.code === 0) {
          sarah.ui.notify("Copied to clipboard (" + text.length + " chars)");
          return "Copied " + text.length + " chars to clipboard.";
        }
      }
      return "Clipboard write unavailable (headless server?). Install: sudo apt install xclip | xsel | wl-clipboard.";
    }
  }
];
