import { i as defineEventHandler, K as readBody, e as createError, r as getActiveRun, f as createEventStream, c as clearActiveRun, R as setActiveRun } from '../../nitro/nitro.mjs';
import { spawn } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import 'node:module';
import 'node:os';
import 'dotenv';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:crypto';
import 'node:async_hooks';
import 'node:url';
import 'node:net';
import '@iconify/utils';
import 'consola';

const STATUSES = /* @__PURE__ */ new Set(["open", "pending", "review", "all"]);
const run_post = defineEventHandler(async (event) => {
  var _a, _b;
  const body = await readBody(event);
  const status = (_a = body == null ? void 0 : body.status) != null ? _a : "";
  if (!STATUSES.has(status)) {
    throw createError({
      statusCode: 400,
      statusMessage: `Invalid status "${body == null ? void 0 : body.status}". Expected one of: open, pending, review, all.`
    });
  }
  const cwd = process.env.AIDEV_CWD;
  if (!cwd) {
    throw createError({ statusCode: 500, statusMessage: "AIDEV_CWD not set" });
  }
  const pkgDir = (_b = process.env.AIDEV_PACKAGE_DIR) != null ? _b : cwd;
  const cli = path.join(pkgDir, "dist", "cli.js");
  if (!fs.existsSync(cli)) {
    throw createError({
      statusCode: 503,
      statusMessage: `aidev CLI not found at ${cli}. Run \`npm run build\` in the aidev repo before triggering runs.`
    });
  }
  if (getActiveRun()) {
    throw createError({
      statusCode: 409,
      statusMessage: "Another aidev run is already in progress. Cancel it before starting a new one."
    });
  }
  const stream = createEventStream(event);
  const startedAt = Date.now();
  const child = spawn(process.execPath, [cli, "run", "--status", status], {
    cwd,
    env: process.env,
    stdio: ["ignore", "pipe", "pipe"]
  });
  setActiveRun(child, status);
  function pump(source, eventName) {
    let buf = "";
    source.setEncoding("utf8");
    source.on("data", (chunk) => {
      buf += chunk;
      let nl = buf.indexOf("\n");
      while (nl !== -1) {
        const line = buf.slice(0, nl).replace(/\r$/, "");
        buf = buf.slice(nl + 1);
        stream.push({ event: eventName, data: line });
        nl = buf.indexOf("\n");
      }
    });
    source.on("end", () => {
      if (buf.length > 0) stream.push({ event: eventName, data: buf.replace(/\r$/, "") });
    });
  }
  pump(child.stdout, "stdout");
  pump(child.stderr, "stderr");
  child.on("error", (err) => {
    stream.push({ event: "error", data: JSON.stringify({ message: err.message, code: err.code }) });
    clearActiveRun(child);
    stream.close();
  });
  child.on("exit", (code, signal) => {
    stream.push({
      event: "exit",
      data: JSON.stringify({ code, signal, durationMs: Date.now() - startedAt })
    });
    clearActiveRun(child);
    stream.close();
  });
  stream.onClosed(() => {
    if (!child.killed && child.exitCode === null) {
      child.kill("SIGTERM");
    }
    clearActiveRun(child);
  });
  return stream.send();
});

export { run_post as default };
//# sourceMappingURL=run.post.mjs.map
