#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { join, resolve } from "node:path";

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

function run(label, command, args) {
  const result = spawnSync(command, args, {
    cwd: root,
    encoding: "utf8",
  });

  process.stdout.write(`\n## ${label}\n`);
  if (result.stdout) process.stdout.write(result.stdout);
  if (result.stderr) process.stdout.write(result.stderr);

  if (result.status !== 0) {
    process.stderr.write(`${label} failed with status ${result.status}\n`);
    process.exit(result.status ?? 1);
  }
}

run("CLI dry-run", process.execPath, ["bin/lazyclaude-ai.js", "--dry-run", "doctor"]);
run("Plugin validation", process.execPath, ["scripts/validate-plugin.mjs"]);
run("LSP doctor", process.execPath, ["plugins/lazyclaude/bin/lazyclaude-lsp-doctor.js"]);

for (const file of [
  "plugins/lazyclaude/lib/ultragoal/paths.mjs",
  "plugins/lazyclaude/lib/ultragoal/state.mjs",
  "plugins/lazyclaude/lib/ultragoal/ledger.mjs",
  "plugins/lazyclaude/lib/ultragoal/cli.mjs",
]) {
  if (!existsSync(join(root, file))) {
    process.stderr.write(`Runtime payload missing: ${file}\n`);
    process.exit(1);
  }
}
process.stdout.write("\nULTRAGOAL_RUNTIME_PASS\n");
process.stdout.write("\nDOCTOR_PASS\n");
