import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";

import { checkProfiles } from "./src/check-plan.mjs";
import { parseCheckRunnerArgs, runCheckRunner, selectTasks } from "./src/check-runner-lib.mjs";

test("package scripts delegate to structured check runner", () => {
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
  assert.equal(pkg.scripts.check, "node scripts/check-runner.mjs --profile check");
  assert.equal(pkg.scripts.validate, "node scripts/check-runner.mjs --profile validate");
  assert.ok(!pkg.scripts.check.includes("&&"));
  assert.ok(!pkg.scripts.validate.includes("&&"));
});

test("check plan exposes grouped tasks", () => {
  assert.ok(checkProfiles.check.length > 80);
  assert.ok(checkProfiles.validate.length > 5);
  assert.ok(checkProfiles.check.some((task) => task.group === "cloud-api"));
  assert.ok(checkProfiles.check.some((task) => task.group === "cloud-web"));
  assert.ok(checkProfiles.check.some((task) => task.group === "runtime-services"));
});

test("check plan runs migrated runtime service TypeScript tests", () => {
  const commands = checkProfiles.check.map((task) => task.command.join(" "));
  assert.ok(commands.some((command) => command.includes("cmd/hwlab-edge-proxy/main.test.ts")));
  assert.ok(commands.some((command) => command.includes("cmd/hwlab-deepseek-responses-bridge/main.test.ts")));
  assert.equal(commands.some((command) => command.includes("cmd/hwlab-edge-proxy/main.ts")), false);
  assert.equal(commands.some((command) => command.includes("cmd/hwlab-deepseek-responses-bridge/main.test.mjs")), false);
});

test("runner filters profile tasks by group", () => {
  const options = parseCheckRunnerArgs(["--profile", "check", "--group", "cloud-api"]);
  const tasks = selectTasks(options);
  assert.ok(tasks.length > 0);
  assert.ok(tasks.every((task) => task.group === "cloud-api"));
});

test("runner rejects unknown group and id instead of reporting an empty successful plan", () => {
  assert.throws(
    () => selectTasks(parseCheckRunnerArgs(["--profile", "check", "--group", "missing-group"])),
    /unknown check group/u
  );
  assert.throws(
    () => selectTasks(parseCheckRunnerArgs(["--profile", "check", "--id", "missing-id"])),
    /unknown check task id/u
  );
});

test("dry-run returns structured JSON without executing tasks", async () => {
  let stdout = "";
  const result = await runCheckRunner(["--profile", "validate", "--group", "repo", "--dry-run"], {
    stdout: { write(chunk) { stdout += chunk; } },
    stderr: { write() {} }
  });
  assert.equal(result.exitCode, 0);
  const payload = JSON.parse(stdout);
  assert.equal(payload.mode, "dry-run");
  assert.equal(payload.profile, "validate");
  assert.ok(payload.tasks.length > 0);
  assert.ok(payload.tasks.every((task) => task.group === "repo"));
});
