import {
  createCliProvider
} from "../chunk-5ZFOKZGR.js";
import "../chunk-2ESYSVXG.js";

// src/providers/apple-firecracker.ts
import { spawn } from "child_process";
var NET_POLICY = process.env.MVM_NET_POLICY ?? "deny";
var mvmProvider = createCliProvider({
  name: "apple-firecracker",
  binary: "mvm",
  createSteps: (name) => [
    ["start", name, "--net-policy", NET_POLICY]
  ],
  postCreate: (name, runExec) => {
    runExec(
      [
        "sh",
        "-c",
        "export NODE_COMPILE_CACHE=/tmp/v8-cache; mkdir -p /tmp/v8-cache; claude --version >/dev/null 2>&1 || true"
      ],
      void 0,
      12e4
    ).catch(() => {
    });
  },
  deleteArgs: (name) => ["delete", name, "--force"],
  execArgs: (name, argv) => ["exec", name, "--", ...argv],
  listArgs: () => ["list", "--json"],
  parseList: (stdout, prefix) => {
    try {
      const vms = JSON.parse(stdout);
      return vms.filter((v) => v.name.startsWith(prefix)).map((v) => v.name);
    } catch {
      return [];
    }
  },
  checkAvailability: async () => {
    try {
      await new Promise((resolve, reject) => {
        const proc = spawn("mvm", ["version"], {
          stdio: ["pipe", "pipe", "pipe"]
        });
        proc.on(
          "close",
          (code) => code === 0 ? resolve() : reject(new Error(`exit ${code}`))
        );
        proc.on("error", reject);
        const t = setTimeout(() => {
          proc.kill("SIGKILL");
          reject(new Error("timeout"));
        }, 5e3);
        proc.on("close", () => clearTimeout(t));
      });
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (msg.includes("ENOENT")) {
        return {
          available: false,
          message: "mvm is not installed. Run: npm install -g @agentstep/mvm && mvm init"
        };
      }
      return { available: false, message: `mvm CLI not available: ${msg}` };
    }
    try {
      const poolOut = await new Promise((resolve, reject) => {
        const proc = spawn("mvm", ["pool", "status"], {
          stdio: ["pipe", "pipe", "pipe"]
        });
        let out = "";
        proc.stdout?.on("data", (buf) => {
          out += buf.toString();
        });
        proc.on(
          "close",
          (code) => code === 0 ? resolve(out) : reject(new Error(`exit ${code}`))
        );
        proc.on("error", reject);
        const t = setTimeout(() => {
          proc.kill("SIGKILL");
          reject(new Error("timeout"));
        }, 5e3);
        proc.on("close", () => clearTimeout(t));
      });
      if (poolOut.includes("0/")) {
        return {
          available: false,
          message: "mvm not ready. Run: mvm init && mvm serve install && mvm pool warm"
        };
      }
    } catch {
      return {
        available: false,
        message: "mvm not ready. Run: mvm init && mvm serve install && mvm pool warm"
      };
    }
    return { available: true };
  }
});
export {
  mvmProvider
};
