import { createConnection } from "node:net";

const WORKER_CREDENTIALS = ["Dada/P0A/worker/ai-gateway"] as const;

export async function receiveWorkerCredentials(input: NodeJS.ReadableStream = process.stdin) {
  const chunks: Buffer[] = [];
  for await (const chunk of input) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  const payload = Buffer.concat(chunks);
  try {
    const parsed = JSON.parse(payload.toString("utf8")) as Record<string, unknown>;
    const names = Object.keys(parsed).sort();
    const expected = [...WORKER_CREDENTIALS].sort();
    if (names.length !== expected.length || names.some((name, index) => name !== expected[index])) {
      throw new Error("Worker credential channel contains an unexpected credential scope.");
    }
    if (expected.some((name) => typeof parsed[name] !== "string")) {
      throw new Error("Worker credential channel contains an invalid credential value.");
    }
    return parsed as Record<(typeof WORKER_CREDENTIALS)[number], string>;
  } finally {
    payload.fill(0);
    for (const chunk of chunks) chunk.fill(0);
    chunks.length = 0;
  }
}

export function initializeWorkerCredentialClient(credentials: Record<(typeof WORKER_CREDENTIALS)[number], string>) {
  const value = credentials["Dada/P0A/worker/ai-gateway"];
  try {
    if (!value) throw new Error("worker_ai_gateway_not_configured");
    return { aiGatewayCredential: Buffer.from(value, "utf8") };
  } finally {
    for (const name of WORKER_CREDENTIALS) credentials[name] = "";
  }
}

export function attachWorkerSupervisorControl(pipeName: string, shutdown: () => Promise<void> | void) {
  const socket = createConnection(`\\\\.\\pipe\\${pipeName}`);
  let pending = "";
  let connected = false;
  const pendingStatuses: string[] = [];
  socket.setEncoding("utf8");
  socket.on("connect", () => {
    connected = true;
    socket.write("ready\n");
    for (const status of pendingStatuses.splice(0)) socket.write(`${status}\n`);
  });
  socket.on("data", (chunk) => {
    pending += chunk;
    if (!pending.includes("\n")) return;
    const [command] = pending.split("\n", 1);
    pending = "";
    if (command === "shutdown") void Promise.resolve(shutdown()).finally(() => socket.end());
  });
  return {
    reportStatus(status: "storage_unavailable") {
      if (socket.destroyed) return;
      if (connected) socket.write(`${status}\n`); else pendingStatuses.push(status);
    },
    socket,
  };
}
