import { mkdtemp, mkdir, rm } from "node:fs/promises";
import { join, resolve } from "node:path";
import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import test from "node:test";
import assert from "node:assert/strict";

const cliPath = resolve(process.cwd(), "bin/antigravity-superpowers.js");

function runCli(args, cwd) {
  return spawnSync(process.execPath, [cliPath, ...args], {
    cwd,
    encoding: "utf8",
  });
}

async function createTempProject(prefix) {
  return mkdtemp(join(tmpdir(), prefix));
}

test("validate passes on freshly initialized project", async () => {
  const projectDir = await createTempProject("agsp-val-pass-");

  try {
    runCli(["init"], projectDir);
    const result = runCli(["validate"], projectDir);
    assert.equal(result.status, 0);
    assert.match(result.stdout, /PASSED/);
    assert.match(result.stdout, /Failed: 0/);
  } finally {
    await rm(projectDir, { recursive: true, force: true });
  }
});

test("validate fails when .agent is missing", async () => {
  const projectDir = await createTempProject("agsp-val-missing-");

  try {
    const result = runCli(["validate"], projectDir);
    assert.equal(result.status, 1);
    assert.match(result.stderr, /No \.agent directory/);
  } finally {
    await rm(projectDir, { recursive: true, force: true });
  }
});

test("validate fails when skills are missing", async () => {
  const projectDir = await createTempProject("agsp-val-incomplete-");

  try {
    // Create partial .agent
    await mkdir(join(projectDir, ".agent"), { recursive: true });
    const result = runCli(["validate"], projectDir);
    assert.equal(result.status, 1);
    assert.match(result.stdout, /FAIL/);
    assert.match(result.stdout, /FAILED/);
  } finally {
    await rm(projectDir, { recursive: true, force: true });
  }
});

test("validate accepts target directory argument", async () => {
  const projectDir = await createTempProject("agsp-val-target-");

  try {
    runCli(["init"], projectDir);
    const result = runCli(["validate", projectDir]);
    assert.equal(result.status, 0);
    assert.match(result.stdout, /PASSED/);
  } finally {
    await rm(projectDir, { recursive: true, force: true });
  }
});
