#!/usr/bin/env node
import assert from "node:assert/strict";
import { access, readdir, readFile } from "node:fs/promises";
import { constants } from "node:fs";
import { join, resolve } from "node:path";
import { spawnSync } from "node:child_process";

const root = resolve(new URL("..", import.meta.url).pathname);
const pluginRoot = join(root, "plugins", "lazyclaude");

async function readJson(path) {
  return JSON.parse(await readFile(path, "utf8"));
}

async function exists(path) {
  await access(path, constants.R_OK);
}

async function main() {
  const manifest = await readJson(join(pluginRoot, ".claude-plugin", "plugin.json"));
  assert.equal(manifest.name, "lazyclaude");
  assert.equal(manifest.skills, "./skills");
  assert.deepEqual(manifest.agents, [
    "./agents/boulder-executor.md",
    "./agents/librarian-researcher.md",
    "./agents/oracle-verifier.md",
    "./agents/prometheus-planner.md",
    "./agents/qa-runner.md",
    "./agents/quality-reviewer.md",
  ]);
  assert.equal("hooks" in manifest, false);
  assert.equal(manifest.mcpServers, "./.mcp.json");
  assert.equal(manifest.lspServers, "./.lsp.json");

  await exists(join(pluginRoot, ".mcp.json"));
  await exists(join(pluginRoot, ".lsp.json"));
  await exists(join(pluginRoot, "bin", "lazyclaude-hook.js"));
  await exists(join(pluginRoot, "bin", "lazyclaude-lsp-doctor.js"));
  await exists(join(pluginRoot, "bin", "lazyclaude-mcp.js"));

  const hooks = await readJson(join(pluginRoot, "hooks", "hooks.json"));
  for (const event of ["SessionStart", "UserPromptSubmit", "PostToolUse", "PostCompact"]) {
    assert.ok(hooks.hooks[event], `missing hook event ${event}`);
  }

  const skills = await readdir(join(pluginRoot, "skills"));
  const agents = await readdir(join(pluginRoot, "agents"));
  assert.ok(skills.length >= 7, "expected at least seven skills");
  assert.ok(agents.length >= 6, "expected at least six agents");

  const claude = spawnSync("claude", ["--version"], { encoding: "utf8" });
  if (claude.status === 0) {
    process.stdout.write(`CLAUDE_VERSION: ${claude.stdout.trim() || claude.stderr.trim()}\n`);
    const validation = spawnSync("claude", ["plugin", "validate", "./plugins/lazyclaude"], {
      cwd: root,
      encoding: "utf8",
    });
    if (validation.stdout) process.stdout.write(validation.stdout);
    if (validation.stderr) process.stdout.write(validation.stderr);
    assert.equal(validation.status, 0, "claude plugin validate must pass");
  } else {
    process.stdout.write("CONTROLLED_SKIP: claude executable unavailable for version probe\n");
  }

  process.stdout.write("VALIDATE_PLUGIN_PASS\n");
}

main().catch((error) => {
  process.stderr.write(`VALIDATE_PLUGIN_FAIL: ${error.message}\n`);
  process.exit(1);
});
