/**
 * @file Tests for server/lib/lane-agents.js: installing the ship-feature-lane
 * agent templates into a lane's .claude/agents/ and git-excluding them. Uses
 * REAL git fixtures (a plain clone AND a `git worktree add` lane) because the
 * exclude-file location depends on git's own git-dir/git-common-dir split —
 * the same distinction E2's merge-driver setup had to get right.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { execFileSync } = require("node:child_process");

const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-agents-"));

const laneAgents = require("../lib/lane-agents");

const g = (cwd, ...args) => {
  const env = { ...process.env };
  delete env.GIT_DIR;
  delete env.GIT_WORK_TREE;
  delete env.GIT_INDEX_FILE;
  delete env.GIT_COMMON_DIR;
  delete env.GIT_OBJECT_DIRECTORY;
  delete env.GIT_ALTERNATE_OBJECT_DIRECTORIES;
  delete env.GIT_PREFIX;
  delete env.GIT_NAMESPACE;
  delete env.GIT_CONFIG_PARAMETERS;
  env.GIT_TERMINAL_PROMPT = "0";
  return execFileSync("git", args, { cwd, encoding: "utf8", env });
};
const gc = (cwd, ...args) => g(cwd, "-c", "user.email=t@h", "-c", "user.name=t", ...args);

after(() => fs.rmSync(ROOT, { recursive: true, force: true }));

describe("installAgents against a plain clone", () => {
  const REPO = path.join(ROOT, "plain-repo");

  before(() => {
    fs.mkdirSync(REPO, { recursive: true });
    g(REPO, "init", "-q", "-b", "main", REPO);
    fs.writeFileSync(path.join(REPO, "README.md"), "hello\n");
    gc(REPO, "add", "-A");
    gc(REPO, "commit", "-qm", "init");
  });

  it("writes both templates and appends the git-exclude line", async () => {
    const result = await laneAgents.installAgents({ cwd: REPO });
    assert.deepEqual(result.installed.sort(), ["qc-local.md", "senior-gate-reviewer.md"]);
    assert.ok(fs.existsSync(path.join(REPO, ".claude", "agents", "qc-local.md")));
    assert.ok(fs.existsSync(path.join(REPO, ".claude", "agents", "senior-gate-reviewer.md")));

    const exclude = fs.readFileSync(path.join(REPO, ".git", "info", "exclude"), "utf8");
    assert.match(exclude, /^\.claude\/agents\/$/m);
  });

  it("is idempotent — a second call does not duplicate the exclude line", async () => {
    await laneAgents.installAgents({ cwd: REPO });
    const exclude = fs.readFileSync(path.join(REPO, ".git", "info", "exclude"), "utf8");
    const matches = exclude.split("\n").filter((line) => line === ".claude/agents/");
    assert.equal(matches.length, 1);
  });

  it("overwrites existing template files on reinstall (not a merge)", async () => {
    const dest = path.join(REPO, ".claude", "agents", "qc-local.md");
    fs.writeFileSync(dest, "stale content from a previous version\n");
    await laneAgents.installAgents({ cwd: REPO });
    const content = fs.readFileSync(dest, "utf8");
    assert.doesNotMatch(content, /stale content/);
  });
});

describe("installAgents against a real git-worktree lane", () => {
  it("writes the exclude line to the SHARED common dir, not the worktree-private one", async () => {
    const wt = require("../lib/worktree");
    const SRC = path.join(ROOT, "wt-src");
    fs.mkdirSync(SRC, { recursive: true });
    g(SRC, "init", "-q", "-b", "main", SRC);
    fs.writeFileSync(path.join(SRC, "README.md"), "hello\n");
    gc(SRC, "add", "-A");
    gc(SRC, "commit", "-qm", "init");

    const wtDir = path.join(ROOT, "wt-lane");
    await wt.addWorktree({ sourceRepo: SRC, dir: wtDir, branch: "feat/agents", base: "main" });

    const result = await laneAgents.installAgents({ cwd: wtDir });
    assert.deepEqual(result.installed.sort(), ["qc-local.md", "senior-gate-reviewer.md"]);
    assert.ok(fs.existsSync(path.join(wtDir, ".claude", "agents", "qc-local.md")));

    // <wtDir>/.git is a FILE for a worktree lane — info/exclude must NOT be
    // written under it. It belongs in the source repo's own .git/info/,
    // shared across every worktree.
    assert.ok(fs.statSync(path.join(wtDir, ".git")).isFile());
    const exclude = fs.readFileSync(path.join(SRC, ".git", "info", "exclude"), "utf8");
    assert.match(exclude, /^\.claude\/agents\/$/m);
  });
});

describe("installAgents against a non-git directory", () => {
  it("throws ENOTGITREPO rather than crashing on a missing .git", async () => {
    const plain = path.join(ROOT, "not-a-repo");
    fs.mkdirSync(plain, { recursive: true });
    await assert.rejects(() => laneAgents.installAgents({ cwd: plain }), { code: "ENOTGITREPO" });
  });
});
