"use strict";
/* Socket Lib - Built with esbuild */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var worktree_exports = {};
__export(worktree_exports, {
  currentBranch: () => currentBranch,
  git: () => git,
  hasCommittedChanges: () => hasCommittedChanges,
  hasStagedOrUnstaged: () => hasStagedOrUnstaged,
  runOne: () => runOne,
  spawnAiAgentsInWorktrees: () => spawnAiAgentsInWorktrees,
  tryGit: () => tryGit
});
module.exports = __toCommonJS(worktree_exports);
var import_node_fs = require("node:fs");
var import_node_path = __toESM(require("node:path"), 1);
var import_message = require("../errors/message");
var import_spawn = require("../spawn/spawn");
var import_errors = require("../spawn/errors");
const DEFAULT_CONCURRENCY = 4;
const MAX_CONCURRENCY = 8;
function currentBranch(repo) {
  return git(repo, "symbolic-ref", "--short", "HEAD");
}
function git(cwd, ...args) {
  const result = (0, import_spawn.spawnSync)("git", args, {
    cwd,
    stdio: "pipe",
    stdioString: true
  });
  return String(result.stdout ?? "").trim();
}
function hasCommittedChanges(worktree, baseBranch) {
  const log = tryGit(worktree, "log", "--oneline", `${baseBranch}..HEAD`);
  if (!log.ok) {
    return false;
  }
  return log.output.trim().length > 0;
}
function hasStagedOrUnstaged(worktree) {
  const status = tryGit(worktree, "status", "--porcelain");
  return status.ok && status.output.trim().length > 0;
}
async function runOne(item, index, worktreeBranch, worktreePath, baseRepo, branch, cleanup, fn) {
  const add = tryGit(
    baseRepo,
    "worktree",
    "add",
    "-b",
    worktreeBranch,
    worktreePath,
    branch
  );
  if (!add.ok) {
    return {
      cleanup: "kept",
      error: new Error(`git worktree add failed: ${add.output}`),
      merged: false,
      status: "rejected",
      worktreePath
    };
  }
  let value;
  let error;
  try {
    value = await fn(item, { branch: worktreeBranch, cwd: worktreePath, index });
  } catch (e) {
    error = e;
  }
  const hasCommitted = hasCommittedChanges(worktreePath, branch);
  const hasUncommitted = hasStagedOrUnstaged(worktreePath);
  let merged = false;
  if (error === void 0 && hasCommitted) {
    const merge = tryGit(baseRepo, "merge", "--ff-only", worktreeBranch);
    if (merge.ok) {
      merged = true;
    } else {
      error = new Error(`git merge --ff-only failed: ${merge.output}`);
    }
  }
  let didCleanup = "kept";
  const shouldCleanup = error === void 0 && (cleanup === "always" || cleanup === "on-empty" && !hasCommitted && !hasUncommitted);
  if (shouldCleanup) {
    const remove = tryGit(baseRepo, "worktree", "remove", worktreePath);
    if (remove.ok) {
      didCleanup = "removed";
      tryGit(baseRepo, "branch", "-D", worktreeBranch);
    }
  }
  if (error !== void 0) {
    return {
      cleanup: didCleanup,
      error,
      merged,
      status: "rejected",
      worktreePath
    };
  }
  return {
    cleanup: didCleanup,
    merged,
    status: "fulfilled",
    value,
    worktreePath
  };
}
async function spawnAiAgentsInWorktrees(items, fn, options) {
  const cleanup = options.cleanup ?? "always";
  const namePrefix = options.namePrefix ?? "agent-task";
  const concurrency = Math.max(
    1,
    Math.min(options.concurrency ?? DEFAULT_CONCURRENCY, MAX_CONCURRENCY)
  );
  const baseRepo = options.baseRepo;
  if (!(0, import_node_fs.existsSync)(import_node_path.default.join(baseRepo, ".git"))) {
    throw new Error(
      `spawnAiAgentsInWorktrees: baseRepo is not a git checkout: ${baseRepo}`
    );
  }
  const branch = options.branch ?? currentBranch(baseRepo);
  const worktreeRoot = options.worktreeRoot ?? import_node_path.default.join(
    process.platform === "win32" ? process.env["TEMP"] ?? "." : "/tmp",
    `${namePrefix}-${Date.now()}`
  );
  const settled = [];
  let cursor = 0;
  async function worker() {
    for (; ; ) {
      const idx = cursor;
      cursor += 1;
      if (idx >= items.length) {
        return;
      }
      const item = items[idx];
      const worktreeBranch = `${namePrefix}-${idx}-${Date.now()}`;
      const worktreePath = import_node_path.default.join(worktreeRoot, `${namePrefix}-${idx}`);
      const result = await runOne(
        item,
        idx,
        worktreeBranch,
        worktreePath,
        baseRepo,
        branch,
        cleanup,
        fn
      );
      settled[idx] = result;
    }
  }
  await Promise.all(Array.from({ length: concurrency }, () => worker()));
  return settled;
}
function tryGit(cwd, ...args) {
  try {
    const output = git(cwd, ...args);
    return { ok: true, output };
  } catch (e) {
    if ((0, import_errors.isSpawnError)(e)) {
      return { ok: false, output: String(e.stderr ?? e.stdout ?? "") };
    }
    return { ok: false, output: (0, import_message.errorMessage)(e) };
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  currentBranch,
  git,
  hasCommittedChanges,
  hasStagedOrUnstaged,
  runOne,
  spawnAiAgentsInWorktrees,
  tryGit
});
