// @bun
import {
  init_slowOperations,
  jsonParse,
  jsonStringify
} from "./chunk-s3hafnk3.js";
import"./chunk-kb3758f7.js";
import"./chunk-9h9k5vz3.js";
import"./chunk-xmpgmeb8.js";
import"./chunk-2kz09j2s.js";
import"./chunk-c0k7b0jw.js";
import"./chunk-hhsxm2yr.js";

// src/server/connectHeadless.ts
init_slowOperations();
function normalizeOutputFormat(value) {
  if (value === "json" || value === "stream-json" || value === "text") {
    return value;
  }
  return "text";
}
async function readStdinIfAvailable() {
  if (process.stdin.isTTY)
    return "";
  const chunks = [];
  for await (const chunk of process.stdin) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString("utf8").trim();
}
function userMessageLine(prompt) {
  return jsonStringify({
    type: "user",
    message: {
      role: "user",
      content: prompt
    },
    parent_tool_use_id: null,
    session_id: ""
  });
}
function denyPermissionLine(requestId) {
  return jsonStringify({
    type: "control_response",
    response: {
      subtype: "success",
      request_id: requestId,
      response: {
        behavior: "deny",
        message: "Headless direct-connect mode cannot approve tool permission prompts."
      }
    }
  });
}
async function toText(data) {
  if (typeof data === "string")
    return data;
  if (data instanceof Blob)
    return await data.text();
  if (data instanceof ArrayBuffer)
    return new TextDecoder().decode(data);
  if (ArrayBuffer.isView(data)) {
    return new TextDecoder().decode(data);
  }
  return String(data);
}
function getResultText(message) {
  return typeof message.result === "string" ? message.result : undefined;
}
async function runConnectHeadless(config, promptArg, outputFormatArg, _interactive) {
  const outputFormat = normalizeOutputFormat(outputFormatArg);
  const prompt = promptArg.trim() || await readStdinIfAvailable();
  if (!prompt) {
    throw new Error("Input must be provided either through stdin or as a prompt argument when using direct-connect print mode");
  }
  const headers = {};
  if (config.authToken) {
    headers.authorization = `Bearer ${config.authToken}`;
  }
  await new Promise((resolve, reject) => {
    const ws = new WebSocket(config.wsUrl, { headers });
    let buffer = "";
    let settled = false;
    const finish = (error) => {
      if (settled)
        return;
      settled = true;
      try {
        ws.close();
      } catch {}
      if (error)
        reject(error);
      else
        resolve();
    };
    ws.addEventListener("open", () => {
      ws.send(userMessageLine(prompt));
    });
    ws.addEventListener("message", (event) => {
      (async () => {
        buffer += await toText(event.data);
        const lines = buffer.split(`
`);
        buffer = lines.pop() ?? "";
        for (const line of lines) {
          const trimmed = line.trim();
          if (!trimmed)
            continue;
          if (outputFormat === "stream-json") {
            process.stdout.write(`${trimmed}
`);
          }
          let parsed;
          try {
            parsed = jsonParse(trimmed);
          } catch {
            continue;
          }
          if (typeof parsed !== "object" || parsed === null || !("type" in parsed)) {
            continue;
          }
          const message = parsed;
          if (message.type === "control_request") {
            const requestId = typeof message.request_id === "string" ? message.request_id : undefined;
            if (requestId) {
              ws.send(denyPermissionLine(requestId));
            }
            continue;
          }
          if (message.type === "result") {
            if (outputFormat === "json") {
              process.stdout.write(`${jsonStringify(message)}
`);
            } else if (outputFormat === "text") {
              const result = getResultText(message);
              if (result)
                process.stdout.write(`${result}
`);
            }
            finish();
          }
        }
      })().catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
    });
    ws.addEventListener("error", () => {
      finish(new Error(`WebSocket connection failed: ${config.wsUrl}`));
    });
    ws.addEventListener("close", () => {
      finish();
    });
  });
}
export {
  runConnectHeadless
};
