import { i as defineEventHandler, K as readBody, e as createError, L as readEnvFile } from '../../../nitro/nitro.mjs';
import { createRequire } from 'node:module';
import { spawnSync } from 'node:child_process';
import * as path from 'node:path';
import * as fs from 'node:fs';
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 AGENT_CLI = {
  claude: ["claude", ["--version"]],
  cursor: ["agent", ["--version"]],
  codex: ["codex", ["--version"]],
  antigravity: ["agy", ["--version"]],
  windsurf: ["windsurf", ["--version"]]
};
function getDistDir() {
  const cwd = process.env.AIDEV_CWD;
  if (!cwd) {
    throw createError({ statusCode: 500, statusMessage: "AIDEV_CWD not set" });
  }
  const dist = path.join(cwd, "dist");
  if (!fs.existsSync(dist)) {
    throw createError({
      statusCode: 503,
      statusMessage: `aidev build artifacts not found at ${dist}. Run \`npm run build\` in the aidev repo before using the dashboard.`
    });
  }
  return dist;
}
function loadAidev(rel) {
  const cwd = process.env.AIDEV_CWD;
  const dist = getDistDir();
  const req = createRequire(path.join(cwd, "package.json"));
  return req(path.join(dist, rel));
}
async function testProvider() {
  const cwd = process.env.AIDEV_CWD;
  const env = readEnvFile(cwd);
  if (!env.exists) {
    return { ok: false, message: `.env.aidev not found at ${env.path}` };
  }
  for (const key of env.keys) {
    delete process.env[key];
  }
  const configMod = loadAidev("config");
  const providersMod = loadAidev("providers");
  const config = configMod.loadConfig(env.path);
  const provider = providersMod.createProvider(config);
  if (typeof provider.fetchAvailableStatuses === "function") {
    const statuses = await provider.fetchAvailableStatuses();
    return {
      ok: true,
      message: `${config.provider}: ${statuses.length} status(es) reachable`
    };
  }
  const tasks = await provider.fetchTasks();
  return {
    ok: true,
    message: `${config.provider}: fetched ${tasks.length} task(s)`
  };
}
function testAnthropicSdk() {
  var _a;
  const cwd = process.env.AIDEV_CWD;
  const env = readEnvFile(cwd);
  if (!env.exists) {
    return { ok: false, message: `.env.aidev not found at ${env.path}` };
  }
  for (const key of env.keys) {
    delete process.env[key];
  }
  const configMod = loadAidev("config");
  configMod.loadConfig(env.path);
  const tokens = configMod.parseAnthropicTokens((_a = process.env.ANTHROPIC_API_KEY) != null ? _a : "");
  return tokens.length > 0 ? {
    ok: true,
    message: `anthropic-sdk: ${tokens.length} API key(s) configured (validated at run time)`
  } : { ok: false, message: "anthropic-sdk: ANTHROPIC_API_KEY is not set" };
}
function testAi(name) {
  if (name === "anthropic-sdk") {
    try {
      return testAnthropicSdk();
    } catch (err) {
      if (err && typeof err === "object" && "statusCode" in err) throw err;
      const message = err instanceof Error ? err.message : String(err);
      return { ok: false, message };
    }
  }
  const cmd = AGENT_CLI[name];
  if (!cmd) {
    return { ok: false, message: `Unknown AI runner: ${name}` };
  }
  const result = spawnSync(cmd[0], cmd[1], {
    encoding: "utf8",
    timeout: 8e3,
    // Don't inherit the UI's stdio — we want to capture the version string.
    stdio: ["ignore", "pipe", "pipe"]
  });
  if (result.error) {
    const code = result.error.code;
    if (code === "ENOENT") {
      return { ok: false, message: `${cmd[0]} not found on PATH` };
    }
    return { ok: false, message: `${cmd[0]}: ${result.error.message}` };
  }
  if (result.status !== 0) {
    const msg = (result.stderr || result.stdout || "").trim();
    return { ok: false, message: `${cmd[0]} exited ${result.status}${msg ? `: ${msg}` : ""}` };
  }
  const out = (result.stdout || "").trim() || "(no output)";
  return { ok: true, message: `${cmd[0]}: ${out}` };
}
const test_post = defineEventHandler(async (event) => {
  var _a;
  const body = (_a = await readBody(event)) != null ? _a : {};
  if (body.provider) {
    try {
      return await testProvider();
    } catch (err) {
      if (err && typeof err === "object" && "statusCode" in err) throw err;
      const message = err instanceof Error ? err.message : String(err);
      return { ok: false, message };
    }
  }
  if (typeof body.ai === "string" && body.ai.length > 0) {
    return testAi(body.ai);
  }
  throw createError({
    statusCode: 400,
    statusMessage: "Specify `provider: true` or `ai: <runner-name>`"
  });
});

export { test_post as default };
//# sourceMappingURL=test.post.mjs.map
