import { afterEach, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

const roots: string[] = [];
const script = resolve(import.meta.dir, "runtime-gitops-verify.mjs");

afterEach(() => {
  while (roots.length > 0) rmSync(roots.pop()!, { recursive: true, force: true });
});

test("architecture capability env and workload matches are not runtime GitOps gates", () => {
  const root = mkdtempSync(join(tmpdir(), "runtime-gitops-verify-"));
  roots.push(root);
  mkdirSync(join(root, "runtime"));
  writeFileSync(join(root, "runtime", "unrelated.yaml"), "apiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: unrelated\n");
  writeFileSync(join(root, "overlay.json"), JSON.stringify({
    runtimePath: "runtime",
    codeAgentRuntime: {
      enabled: true,
      kafkaEventBridge: { enabled: true },
    },
  }));

  const result = spawnSync(process.execPath, [script], {
    cwd: root,
    env: { ...process.env, UNIDESK_RUNTIME_GITOPS_OVERLAY_FILE: join(root, "overlay.json") },
    encoding: "utf8",
  });

  expect(result.status).toBe(0);
  expect(result.stderr).toContain('"code-agent-runtime-kafka-event-bridge-enabled"');
  expect(result.stderr).not.toContain("capability-env-invalid");
  expect(result.stderr).not.toContain("workload-missing");
  expect(result.stderr).not.toContain("authority-invalid");
});
