import { shq } from "./remote-ssh.mjs";
import { remoteTransport } from "./remote-ssh.mjs";

export function buildStdinBlobReceiveScript(installLines = []) {
  return [
    "set -euo pipefail",
    "tmp=$(mktemp)",
    'trap \'rm -f "$tmp"\' EXIT',
    'cat >"$tmp"',
    '[ -s "$tmp" ] || { echo seat-blob-empty; exit 1; }',
    ...installLines,
  ].join("\n");
}

export function sshExecStdinBlob(cfg, installLines, blob, deps = {}) {
  const transport = deps.remoteTransport ?? remoteTransport;
  const script = buildStdinBlobReceiveScript(installLines);
  const buf = Buffer.isBuffer(blob) ? blob : Buffer.from(String(blob), "utf8");
  return transport(cfg, `bash -c ${shq(script)}`, {
    input: buf,
    timeoutSec: cfg.ssh_exec_timeout_sec ?? 1800,
    maxBuffer: deps.maxBuffer ?? 64 * 1024 * 1024,
  }, deps);
}

export function containsCredentialMarkers(text) {
  const s = String(text);
  if (/FRAME\s+codex_auth/.test(s)) return true;
  if (/FRAME\s+account_tar/.test(s)) return true;
  if (/printf\s+'%s'\s+'[A-Za-z0-9+/=]{80,}'/.test(s)) return true;
  if (/base64\.b64decode\([^)]{80,}\)/.test(s)) return true;
  return false;
}

export function assertCommandFreeOfBlob(command, blob) {
  const buf = Buffer.isBuffer(blob) ? blob : Buffer.from(String(blob), "utf8");
  if (buf.length === 0) return;
  if (command.includes(buf.toString("utf8"))) {
    throw new Error("seat-transfer: credential bytes in command");
  }
  const b64 = buf.toString("base64");
  if (b64.length >= 32 && command.includes(b64)) {
    throw new Error("seat-transfer: credential base64 in command");
  }
}
