/**
 * @file Installs the ship-feature-lane pipeline's agent templates
 * (qc-local, senior-gate-reviewer) into a lane's own .claude/agents/, so a
 * driving session can launch them by subagent_type. Plain file I/O except
 * for one git call — resolving where a worktree lane's shared info/exclude
 * actually lives, the same git-dir/git-common-dir distinction E2's
 * lane-sync.js had to get right for info/attributes.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

const fs = require("node:fs");
const path = require("node:path");
const { git } = require("./worktree");

const TEMPLATE_DIR = path.join(__dirname, "..", "data", "agent-templates", "ship-feature-lane");
const TEMPLATE_FILES = ["qc-local.md", "senior-gate-reviewer.md"];
const EXCLUDE_LINE = ".claude/agents/";

/** The dir shared across every worktree of a repo — where info/exclude
 *  lives (same as info/attributes; MERGE_HEAD/HEAD/the index are the only
 *  per-worktree-private state, not this). */
async function commonGitDir(cwd) {
  const result = await git(cwd, ["rev-parse", "--git-common-dir"]);
  const dir = result.stdout.trim();
  return path.isAbsolute(dir) ? dir : path.join(cwd, dir);
}

/**
 * Copy both agent templates into `<lane.cwd>/.claude/agents/` (overwriting
 * any existing copy — this is a reinstall, not a merge) and idempotently
 * git-exclude that directory in the shared common git dir.
 *
 * @param {{cwd: string}} lane
 * @returns {Promise<{installed: string[]}>}
 */
async function installAgents(lane) {
  if (!fs.existsSync(path.join(lane.cwd, ".git"))) {
    throw Object.assign(new Error(`lane has no .git — not a git repository: ${lane.cwd}`), {
      code: "ENOTGITREPO",
    });
  }

  const dest = path.join(lane.cwd, ".claude", "agents");
  fs.mkdirSync(dest, { recursive: true });
  const installed = [];
  for (const name of TEMPLATE_FILES) {
    fs.copyFileSync(path.join(TEMPLATE_DIR, name), path.join(dest, name));
    installed.push(name);
  }

  const infoDir = path.join(await commonGitDir(lane.cwd), "info");
  fs.mkdirSync(infoDir, { recursive: true });
  const excludePath = path.join(infoDir, "exclude");
  const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, "utf8") : "";
  const lines = existing.split("\n").filter(Boolean);
  if (!lines.includes(EXCLUDE_LINE)) {
    lines.push(EXCLUDE_LINE);
    fs.writeFileSync(excludePath, lines.join("\n") + "\n");
  }

  return { installed };
}

module.exports = { installAgents };
