/* What the studio server asked of the runtime beyond the web standards, in Node's own terms: starting a program,
   finding one on PATH, pausing, writing a request body to disk and serving a file with Range. It stood on `Bun.spawn`,
   `Bun.which`, `Bun.sleep`, `Bun.write` and `Bun.file`; none of that is left, so the same code runs under bun today
   and under Node when bun leaves the machine (docs/specs/machine-agent.md, 5.4). */

import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { stat } from "node:fs/promises";
import { constants } from "node:os";
import { extname } from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { which } from "../../../tools/lib/platform.mjs";

export { which };
export { setTimeout as sleep } from "node:timers/promises";

/* --- programs ------------------------------------------------------------------------------ */

/** "pipe" gives a stream, "ignore" drops the output, "inherit" shares ours, a number is an open file descriptor */
type Stdio = "pipe" | "ignore" | "inherit" | number;

export type SpawnOptions = {
  cwd?: string;
  env?: Record<string, string | undefined>;
  stdin?: Stdio;
  stdout?: Stdio;
  stderr?: Stdio;
  /** its own process group, so it outlives this process and a kill reaches its children */
  detached?: boolean;
};

export type Proc = {
  pid: number;
  /** what the program printed; an empty stream unless it was started with "pipe" */
  stdout: ReadableStream<Uint8Array>;
  stderr: ReadableStream<Uint8Array>;
  /** the exit code; a program killed by a signal exits with 128 + the signal's number, as a shell reports it */
  exited: Promise<number>;
  kill(signal?: NodeJS.Signals | number): void;
  /** this process may end without waiting for the program */
  unref(): void;
};

const emptyStream = () => new ReadableStream<Uint8Array>({ start: c => c.close() });
const webStream = (s: Readable | null) =>
  s ? (Readable.toWeb(s) as unknown as ReadableStream<Uint8Array>) : emptyStream();

/** Starts a program (argv, never a shell). Throws right away when it cannot start, as `Bun.spawn` did, so a missing
 *  program reaches the caller's try/catch and not an unhandled event. stdin and stdout default to what Bun's did:
 *  stdin closed, stdout a pipe, stderr shared with this process. */
export function spawn(cmd: string[], o: SpawnOptions = {}): Proc {
  const [bin, ...args] = cmd;
  const child = nodeSpawn(bin, args, {
    cwd: o.cwd,
    env: o.env,
    detached: o.detached,
    stdio: [o.stdin ?? "ignore", o.stdout ?? "pipe", o.stderr ?? "inherit"],
    windowsHide: true,
  });
  const exited = new Promise<number>(resolve => {
    child.once("error", () => resolve(127));
    child.once("exit", (code, signal) => resolve(code ?? 128 + (signal ? (constants.signals[signal] ?? 0) : 0)));
  });
  if (child.pid === undefined) {
    throw Object.assign(new Error(`não deu para iniciar "${bin}": ele existe e está no PATH?`), { code: "ENOENT" });
  }
  return {
    pid: child.pid,
    stdout: webStream(child.stdout),
    stderr: webStream(child.stderr),
    exited,
    kill: signal => void child.kill(signal),
    unref: () => child.unref(),
  };
}

/** Runs a program to the end and returns what it printed. Throws when it cannot start. */
export function spawnSync(cmd: string[], o: Pick<SpawnOptions, "cwd" | "env"> = {}) {
  const r = nodeSpawnSync(cmd[0], cmd.slice(1), { cwd: o.cwd, env: o.env, windowsHide: true });
  if (r.error) throw r.error;
  return {
    stdout: r.stdout,
    stderr: r.stderr,
    exitCode: r.status ?? 128 + (r.signal ? (constants.signals[r.signal] ?? 0) : 0),
  };
}

/** A short stable name for a string (a cache file's), where `Bun.hash` made one */
export const hashKey = (s: string) => createHash("sha1").update(s).digest("base64url").slice(0, 11);

/* --- files --------------------------------------------------------------------------------- */

/** An upload's body written to `dest` without holding it in memory; returns the bytes written (0: nothing came). */
export async function writeBody(dest: string, body: ReadableStream<Uint8Array>): Promise<number> {
  let bytes = 0;
  const count = new Transform({
    transform(chunk, _enc, done) {
      bytes += chunk.length;
      done(null, chunk);
    },
  });
  await pipeline(Readable.fromWeb(body as never), count, createWriteStream(dest));
  return bytes;
}

/* a file as a response, with Range: tools/lib/file-response.mjs (the agent serves files to the hosted page with it too) */
export { fileResponse, mimeOf, parseRange } from "../../../tools/lib/file-response.mjs";
