/* 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;
}

const MIME: Record<string, string> = {
  ".mp4": "video/mp4",
  ".m4v": "video/mp4",
  ".mov": "video/quicktime",
  ".webm": "video/webm",
  ".mkv": "video/x-matroska",
  ".avi": "video/x-msvideo",
  ".mp3": "audio/mpeg",
  ".wav": "audio/wav",
  ".m4a": "audio/mp4",
  ".aac": "audio/aac",
  ".flac": "audio/flac",
  ".ogg": "audio/ogg",
  ".opus": "audio/ogg",
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".webp": "image/webp",
  ".gif": "image/gif",
  ".svg": "image/svg+xml",
  ".html": "text/html; charset=utf-8",
  ".css": "text/css; charset=utf-8",
  ".js": "text/javascript; charset=utf-8",
  ".json": "application/json; charset=utf-8",
  ".txt": "text/plain; charset=utf-8",
  ".md": "text/markdown; charset=utf-8",
  ".woff": "font/woff",
  ".woff2": "font/woff2",
  ".ttf": "font/ttf",
  ".pdf": "application/pdf",
};
export const mimeOf = (file: string) => MIME[extname(file).toLowerCase()] ?? "application/octet-stream";

/** `Range: bytes=a-b | a- | -n` against a file of `size` bytes: the inclusive slice, "none" for no (or an unusable)
 *  header, "unsatisfiable" when it lies outside the file. */
export function parseRange(header: string | null | undefined, size: number) {
  const m = /^bytes=(\d*)-(\d*)$/.exec(header?.trim() ?? "");
  if (!m || (m[1] === "" && m[2] === "")) return "none" as const;
  const start = m[1] === "" ? Math.max(0, size - Number(m[2])) : Number(m[1]);
  const end = m[1] === "" || m[2] === "" ? size - 1 : Math.min(Number(m[2]), size - 1);
  return start >= size || start > end ? ("unsatisfiable" as const) : { start, end };
}

/** A file as a response, null when it is not a file. Answers Range itself (206, or 416 outside the file) because a
 *  video or audio player seeks with it, and streams the bytes: a long export is never read whole. `headers` are
 *  added on top of the content-type taken from the extension. */
export async function fileResponse(abs: string, req?: Request, headers: Record<string, string> = {}) {
  const info = await stat(abs).catch(() => null);
  if (!info?.isFile()) return null;
  const size = info.size;
  const h = new Headers({ "content-type": mimeOf(abs), "accept-ranges": "bytes" });
  for (const [k, v] of Object.entries(headers)) h.set(k, v);
  const range = parseRange(req?.headers.get("range"), size);
  if (range === "unsatisfiable")
    return new Response(null, { status: 416, headers: { "content-range": `bytes */${size}` } });
  const [start, end] = range === "none" ? [0, size - 1] : [range.start, range.end];
  h.set("content-length", String(size === 0 ? 0 : end - start + 1));
  if (range !== "none") h.set("content-range", `bytes ${start}-${end}/${size}`);
  const body =
    size === 0
      ? null
      : (Readable.toWeb(createReadStream(abs, { start, end })) as unknown as ReadableStream<Uint8Array>);
  return new Response(body, { status: range === "none" ? 200 : 206, headers: h });
}
