import { afterEach, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdtempSync, mkdirSync, readFileSync, 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-postprocess.mjs");

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

test("patches fixed Kafka transport settings without architecture capability env", () => {
  const root = mkdtempSync(join(tmpdir(), "runtime-gitops-postprocess-"));
  roots.push(root);
  const runtimeDir = join(root, "runtime");
  mkdirSync(runtimeDir);
  writeFileSync(join(root, "overlay.json"), JSON.stringify(overlay("runtime")));
  writeFileSync(join(runtimeDir, "cloud-api.yaml"), deploymentYaml("hwlab-cloud-api"));
  writeFileSync(join(runtimeDir, "cloud-web.yaml"), `apiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: unchanged\n---\n${deploymentYaml("hwlab-cloud-web")}`);
  writeFileSync(join(runtimeDir, "list.yaml"), `apiVersion: v1\nkind: List\nitems:\n${listItem(deploymentYaml("hwlab-cloud-api"))}\n`);
  writeFileSync(join(runtimeDir, "json-workload.yaml"), `${JSON.stringify(Bun.YAML.parse(deploymentYaml("hwlab-cloud-api")), null, 2)}\n`);

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

  if (result.status !== 0) throw new Error(result.stderr);
  expect(result.stderr).toContain('"codeAgentRuntimeChanged":true');

  const api = Bun.YAML.parse(readFileSync(join(runtimeDir, "cloud-api.yaml"), "utf8")) as any;
  expect(envValues(api)).toMatchObject({
    HWLAB_KAFKA_ENABLED: "true",
    HWLAB_KAFKA_AGENTRUN_EVENT_CONSUME_ENABLED: "true",
    HWLAB_KAFKA_PROJECTOR_GROUP_ID: "hwlab-projector",
    HWLAB_KAFKA_HWLAB_EVENT_GROUP_ID: "hwlab-events",
  });
  expect(architectureEnvNames(api)).toEqual([]);

  const multiDocs = readFileSync(join(runtimeDir, "cloud-web.yaml"), "utf8").split(/^---$/mu).map((document) => Bun.YAML.parse(document) as any);
  expect(multiDocs[0].kind).toBe("ConfigMap");
  expect(envValues(multiDocs[1])).toEqual({ EXISTING: "preserved" });

  const list = Bun.YAML.parse(readFileSync(join(runtimeDir, "list.yaml"), "utf8")) as any;
  expect(list.kind).toBe("List");
  expect(architectureEnvNames(list.items[0])).toEqual([]);

  const jsonText = readFileSync(join(runtimeDir, "json-workload.yaml"), "utf8");
  expect(jsonText.startsWith("{\n")).toBe(true);
  expect(architectureEnvNames(JSON.parse(jsonText))).toEqual([]);

  const afterFirstRun = snapshot(runtimeDir);
  const second = spawnSync(process.execPath, [script], {
    cwd: root,
    env: { ...process.env, UNIDESK_RUNTIME_GITOPS_OVERLAY_FILE: join(root, "overlay.json") },
    encoding: "utf8",
  });
  if (second.status !== 0) throw new Error(second.stderr);
  expect(second.stderr).toContain('"codeAgentRuntimeChanged":false');
  expect(snapshot(runtimeDir)).toEqual(afterFirstRun);
});

function overlay(runtimePath: string) {
  return {
    runtimePath,
    codeAgentRuntime: {
      enabled: true,
      kafkaEventBridge: {
        enabled: true,
        transactionalProjectorConsumerGroupId: "hwlab-projector",
        hwlabEventConsumerGroupId: "hwlab-events",
        transactionalProjector: { heartbeatIntervalMs: 2000 },
        projectionOutboxRelay: { intervalMs: 250, batchSize: 100, leaseMs: 30000, sendTimeoutMs: 10000, retryBackoffMs: 1000 },
        projectionRealtime: { outboxTailBatchSize: 100, sseHeartbeatMs: 1000, sseDrainTimeoutMs: 5000 },
      },
    },
  };
}

function deploymentYaml(name: string) {
  return `apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: ${name}\n  labels:\n    app.kubernetes.io/name: ${name}\nspec:\n  template:\n    spec:\n      containers:\n        - name: ${name}\n          env:\n            - name: EXISTING\n              value: preserved\n`;
}

function listItem(value: string) {
  const [first, ...rest] = value.trimEnd().split("\n");
  return [`  - ${first}`, ...rest.map((line) => `    ${line}`)].join("\n");
}

function envValues(workload: any) {
  return Object.fromEntries(workload.spec.template.spec.containers[0].env.map((item: any) => [item.name, item.value]));
}

function architectureEnvNames(workload: any) {
  const forbidden = new Set([
    "HWLAB_KAFKA_DIRECT_PUBLISH_ENABLED",
    "HWLAB_WORKBENCH_LIVE_KAFKA_SSE_ENABLED",
    "HWLAB_WORKBENCH_KAFKA_REFRESH_REPLAY_ENABLED",
    "HWLAB_KAFKA_TRANSACTIONAL_PROJECTOR_ENABLED",
    "HWLAB_KAFKA_PROJECTION_OUTBOX_RELAY_ENABLED",
    "HWLAB_WORKBENCH_PROJECTION_REALTIME_ENABLED",
  ]);
  return workload.spec.template.spec.containers[0].env.map((item: any) => item.name).filter((name: string) => forbidden.has(name));
}

function snapshot(runtimeDir: string) {
  return ["cloud-api.yaml", "cloud-web.yaml", "list.yaml", "json-workload.yaml"].map((name) => readFileSync(join(runtimeDir, name), "utf8"));
}
