#!/usr/bin/env bun
import assert from "node:assert/strict";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
  DEV_DB_ENV_CONTRACT,
  parseDbUrlContract
} from "../internal/cloud/db-contract.ts";
import {
  DEV_CODE_AGENT_PROVIDER_CONTRACT,
  codeAgentSecretRefPlaceholder
} from "../internal/cloud/code-agent-contract.ts";
import { HWLAB_M3_IO_API_BASE_URL_ENV } from "../skills/hwlab-agent-runtime/scripts/src/m3-io-skill-client.mjs";
import {
  ENVIRONMENT_DEV,
  TABLES,
  validateRequest,
  validateResponse
} from "../internal/protocol/index.mjs";
import { readStructuredFile } from "./src/structured-config.mjs";

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");

async function parseJSONFiles(dir, { requireSchema = true } = {}) {
  const entries = await readdir(path.join(repoRoot, dir), { withFileTypes: true });
  const parsed = [];
  for (const entry of entries) {
    if (!entry.isFile() || !entry.name.endsWith(".json")) {
      continue;
    }
    const relativePath = path.join(dir, entry.name);
    const raw = await readFile(path.join(repoRoot, relativePath), "utf8");
    const doc = JSON.parse(raw);
    if (requireSchema) {
      assert.ok(doc.$schema, `${relativePath} missing $schema`);
      assert.ok(doc.$id, `${relativePath} missing $id`);
    }
    parsed.push({ relativePath, doc });
  }
  return parsed;
}

async function parseJSONSchemaFiles(dir) {
  const parsed = [];
  for (const item of await parseJSONFiles(dir, { requireSchema: false })) {
    if (!item.doc.$schema || !item.doc.$id) {
      continue;
    }
    parsed.push(item);
  }
  return parsed;
}

async function parseDeployManifest(relativePath) {
  const doc = await readStructuredFile(repoRoot, relativePath);
  assert.equal(doc.manifestVersion, "v1", `${relativePath} manifestVersion`);
  assert.equal(doc.environment, ENVIRONMENT_DEV, `${relativePath} environment`);
  assert.equal(Object.hasOwn(doc, "commitId"), false, `${relativePath} commitId must stay in artifact catalog`);
  assert.ok(Array.isArray(doc.services) && doc.services.length >= 1, `${relativePath} services`);
  return doc;
}

async function parseK8sList(relativePath) {
  const doc = await readStructuredFile(repoRoot, relativePath);
  assert.equal(doc.kind, "List", `${relativePath} kind`);
  assert.ok(Array.isArray(doc.items), `${relativePath} items`);
  return doc;
}

function assertUnique(name, values) {
  assert.equal(new Set(values).size, values.length, `${name} must be unique`);
}

function assertCommonSchema(commonSchema) {
  assert.deepEqual(commonSchema.$defs.environment.enum, [ENVIRONMENT_DEV]);
}

function assertDeploySchema(deploySchema) {
  assert.equal(deploySchema.properties.endpoint.const, "http://74.48.78.17:16667");
  assert.ok(deploySchema.required.includes("health"), "deploy schema requires health source");
  assert.ok(deploySchema.required.includes("publicEndpoints"), "deploy schema requires public endpoint source");
  assert.ok(deploySchema.required.includes("frp"), "deploy schema requires frp source");
  assert.ok(deploySchema.required.includes("k3s"), "deploy schema requires k3s source");
  assert.equal(deploySchema.required.includes("commitId"), false, "deploy schema must not require generated commitId");
  assert.equal(deploySchema.$defs.service.required.includes("image"), false, "deploy service schema must not require generated image");
  assert.equal(deploySchema.$defs.health.properties.path.const, "/health/live", "deploy health path source");
}

function assertNoDeployArtifactIdentity(service, serviceId) {
  const forbiddenServiceFields = ["image", "imageTag", "digest", "commitId", "sourceCommitId"];
  const forbiddenEnvFields = ["HWLAB_COMMIT_ID", "HWLAB_IMAGE", "HWLAB_IMAGE_TAG", "HWLAB_IMAGE_DIGEST", "HWLAB_REVISION", "HWLAB_BUILD_CREATED_AT", "HWLAB_BUILD_SOURCE", "HWLAB_SKILLS_COMMIT_ID"];
  for (const field of forbiddenServiceFields) {
    assert.equal(Object.hasOwn(service, field), false, `${serviceId}.${field} must stay in artifact catalog or rendered runtime manifests`);
  }
  for (const field of forbiddenEnvFields) {
    assert.equal(Object.hasOwn(service.env ?? {}, field), false, `${serviceId}.env.${field} must be rendered from artifact catalog`);
  }
}

function assertEnvelopeValidation() {
  validateRequest({
    jsonrpc: "2.0",
    id: "req_01J00000000000000000000000",
    method: "hardware.operation.request",
    params: {
      projectId: "prj_01J00000000000000000000000"
    },
    meta: {
      traceId: "trc_01J00000000000000000000000",
      serviceId: "hwlab-cloud-api",
      environment: "dev"
    }
  });

  validateResponse({
    jsonrpc: "2.0",
    id: "req_01J00000000000000000000000",
    result: {
      accepted: true
    },
    meta: {
      traceId: "trc_01J00000000000000000000000",
      serviceId: "hwlab-cloud-api",
      environment: "dev"
    }
  });

  assert.throws(
    () =>
      validateResponse({
        jsonrpc: "2.0",
        id: "req_01J00000000000000000000000",
        result: {},
        error: { code: -32000, message: "bad" },
        meta: {
          traceId: "trc_01J00000000000000000000000",
          serviceId: "hwlab-cloud-api",
          environment: "dev"
        }
      }),
    /exactly one/
  );
}

const schemas = await parseJSONSchemaFiles("protocol/schemas");
const deploySchemas = await parseJSONSchemaFiles("deploy");
const deployManifest = await parseDeployManifest("deploy/deploy.yaml");
const k8sServices = await parseK8sList("deploy/k8s/base/services.yaml");
const k8sWorkloads = await parseK8sList("deploy/k8s/base/workloads.yaml");
const docsByName = new Map([...schemas, ...deploySchemas].map((item) => [path.basename(item.relativePath), item.doc]));

assert.ok(schemas.length >= 13, "expected protocol schemas");
assert.ok(TABLES.includes("patch_panel_status"), "frozen tables must include patch_panel_status");
assertUnique("tables", TABLES);
assertCommonSchema(docsByName.get("common.json"));
assertDeploySchema(docsByName.get("deploy.schema.json"));
assertEnvelopeValidation();
const deployServicesById = new Map(deployManifest.services.map((service) => [service.serviceId, service]));
assert.equal(deployServicesById.has("hwlab-agent-skills"), true);
for (const removedServiceId of ["hwlab-agent-mgr", "hwlab-agent-worker", "hwlab-gateway-simu", "hwlab-box-simu", "hwlab-patch-panel", "hwlab-router", "hwlab-tunnel-client"]) {
  assert.equal(deployServicesById.has(removedServiceId), false, `${removedServiceId} is removed from default deploy services`);
  assert.equal(getWorkload(k8sWorkloads, removedServiceId), null, `${removedServiceId} is removed from default workload manifests`);
  assert.equal(listItems(k8sServices).some((item) => item?.metadata?.labels?.["hwlab.pikastech.local/service-id"] === removedServiceId), false, `${removedServiceId} is removed from default service manifests`);
}

const cloudApi = deployServicesById.get("hwlab-cloud-api");
const cloudApiWorkload = getWorkload(k8sWorkloads, "hwlab-cloud-api");
const cloudApiContainer = cloudApiWorkload?.spec?.template?.spec?.containers?.find((entry) => entry.name === "hwlab-cloud-api");
const cloudApiWorkloadEnv = getWorkloadEnv(k8sWorkloads, "hwlab-cloud-api");
cloudApiWorkloadEnv.__volumeMounts = cloudApiContainer?.volumeMounts ?? [];
cloudApiWorkloadEnv.__volumes = cloudApiWorkload?.spec?.template?.spec?.volumes ?? [];
cloudApiWorkloadEnv.__podContainers = cloudApiWorkload?.spec?.template?.spec?.containers ?? [];
cloudApiWorkloadEnv.__initContainers = cloudApiWorkload?.spec?.template?.spec?.initContainers ?? [];
cloudApiWorkloadEnv.__deploymentStrategy = cloudApiWorkload?.spec?.strategy ?? null;
cloudApiWorkloadEnv.__workspacePvc = getWorkload(k8sWorkloads, DEV_CODE_AGENT_PROVIDER_CONTRACT.workspace.claimName);
assert.equal(deployManifest.health.path, "/health/live", "deploy health source path");
assert.equal(deployManifest.publicEndpoints.frontend.url, "http://74.48.78.17:16666", "deploy frontend endpoint");
assert.equal(deployManifest.publicEndpoints.api.url, "http://74.48.78.17:16667", "deploy api endpoint");
assert.equal(deployManifest.frp.proxies.find((proxy) => proxy.endpointId === "frontend")?.remotePort, 16666, "deploy frontend frp remote port");
assert.equal(deployManifest.frp.proxies.find((proxy) => proxy.endpointId === "api")?.remotePort, 16667, "deploy api frp remote port");
assert.ok(
  deployManifest.k3s.serviceMappings.some((mapping) => mapping.serviceId === "hwlab-edge-proxy" && mapping.port === 6667),
  "deploy edge proxy k3s mapping"
);
assert.equal(cloudApi.healthPath, "/health/live", "cloud-api health path");
for (const service of deployManifest.services) assertNoDeployArtifactIdentity(service, service.serviceId);
assert.equal(cloudApi.env.HWLAB_CLOUD_DB_URL, "secretRef:hwlab-cloud-api-dev-db/database-url", "cloud-api DB URL must be a Secret reference placeholder");
assert.equal(
  cloudApi.env.HWLAB_CLOUD_DB_SSL_MODE,
  DEV_DB_ENV_CONTRACT.nonSecretDefaults.HWLAB_CLOUD_DB_SSL_MODE,
  "cloud-api DEV DB SSL mode"
);
assert.equal(cloudApi.env.HWLAB_CLOUD_DB_CONTRACT, "dev-redacted-presence-only", "cloud-api DB contract marker");
assert.equal(cloudApi.env.HWLAB_CLOUD_RUNTIME_ADAPTER, "postgres", "cloud-api runtime durable adapter");
assert.equal(cloudApi.env.HWLAB_CLOUD_RUNTIME_DURABLE, "true", "cloud-api runtime durable flag");
assert.equal(cloudApi.env.HWLAB_M3_IO_CONTROL_ENABLED, "false", "legacy M3 IO control is disabled in default deploy config");
assert.equal(cloudApi.env.HWLAB_M3_GATEWAY_SIMU_1_URL, undefined, "legacy gateway simulator URL is removed from default deploy config");
assert.equal(cloudApi.env.HWLAB_M3_GATEWAY_SIMU_2_URL, undefined, "legacy gateway simulator URL is removed from default deploy config");
assert.equal(cloudApi.env.HWLAB_M3_PATCH_PANEL_URL, undefined, "legacy patch-panel URL is removed from default deploy config");
assert.equal(
  cloudApiWorkloadEnv.HWLAB_CLOUD_DB_SSL_MODE?.value,
  DEV_DB_ENV_CONTRACT.nonSecretDefaults.HWLAB_CLOUD_DB_SSL_MODE,
  "cloud-api workload DEV DB SSL mode"
);
assert.equal(cloudApiWorkloadEnv.HWLAB_CLOUD_RUNTIME_ADAPTER?.value, "postgres", "cloud-api workload runtime durable adapter");
assert.equal(cloudApiWorkloadEnv.HWLAB_CLOUD_RUNTIME_DURABLE?.value, "true", "cloud-api workload runtime durable flag");
assert.equal(cloudApiWorkloadEnv.HWLAB_M3_IO_CONTROL_ENABLED?.value, "false", "legacy M3 IO control is disabled in default workload config");
assert.equal(cloudApiWorkloadEnv.HWLAB_M3_GATEWAY_SIMU_1_URL, undefined, "legacy gateway simulator URL is removed from default workload config");
assert.equal(cloudApiWorkloadEnv.HWLAB_M3_GATEWAY_SIMU_2_URL, undefined, "legacy gateway simulator URL is removed from default workload config");
assert.equal(cloudApiWorkloadEnv.HWLAB_M3_PATCH_PANEL_URL, undefined, "legacy patch-panel URL is removed from default workload config");
assert.equal(cloudApi.env.HWLAB_CLOUD_DB_SERVICE_NAME, undefined, "cloud-api DB alias service name is optional");
assert.equal(cloudApi.env.HWLAB_CLOUD_DB_SERVICE_NAMESPACE, undefined, "cloud-api DB alias namespace is optional");
assert.equal(cloudApi.env.HWLAB_CLOUD_DB_HOST, undefined, "cloud-api DB alias host is optional");
assert.equal(cloudApi.env.HWLAB_CLOUD_DB_PORT, undefined, "cloud-api DB alias port is optional");
assert.equal(cloudApiWorkloadEnv.HWLAB_CLOUD_DB_SERVICE_NAME, undefined, "cloud-api workload DB alias service name is optional");
assert.equal(cloudApiWorkloadEnv.HWLAB_CLOUD_DB_SERVICE_NAMESPACE, undefined, "cloud-api workload DB alias namespace is optional");
assert.equal(cloudApiWorkloadEnv.HWLAB_CLOUD_DB_HOST, undefined, "cloud-api workload DB alias host is optional");
assert.equal(cloudApiWorkloadEnv.HWLAB_CLOUD_DB_PORT, undefined, "cloud-api workload DB alias port is optional");
assertCloudApiDbOptionalAlias(k8sServices);
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_PROVIDER, DEV_CODE_AGENT_PROVIDER_CONTRACT.codeAgentProvider, "cloud-api Code Agent provider");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_MODEL, DEV_CODE_AGENT_PROVIDER_CONTRACT.model, "cloud-api Code Agent model");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_DEFAULT_PROVIDER_PROFILE, DEV_CODE_AGENT_PROVIDER_CONTRACT.profiles.defaultProfile, "cloud-api default provider profile");
assert.equal(cloudApi.env[DEV_CODE_AGENT_PROVIDER_CONTRACT.profiles.deepSeekModelEnv], "deepseek-chat", "cloud-api DeepSeek profile model");
assert.equal(cloudApi.env[DEV_CODE_AGENT_PROVIDER_CONTRACT.profiles.deepSeekBaseUrlEnv], DEV_CODE_AGENT_PROVIDER_CONTRACT.profiles.deepSeekBaseUrl, "cloud-api DeepSeek profile base URL");
assert.equal(cloudApi.env[DEV_CODE_AGENT_PROVIDER_CONTRACT.profiles.codexApiModelEnv], DEV_CODE_AGENT_PROVIDER_CONTRACT.model, "cloud-api codex-api profile model");
assert.equal(cloudApi.env[DEV_CODE_AGENT_PROVIDER_CONTRACT.profiles.codexApiBaseUrlEnv], DEV_CODE_AGENT_PROVIDER_CONTRACT.egress.defaultBaseUrl, "cloud-api codex-api profile base URL");
assert.equal(cloudApi.env[DEV_CODE_AGENT_PROVIDER_CONTRACT.forwarder.upstreamEnv], DEV_CODE_AGENT_PROVIDER_CONTRACT.forwarder.upstreamBaseUrl, "cloud-api codex-api upstream base URL");
assert.equal(cloudApi.env[DEV_CODE_AGENT_PROVIDER_CONTRACT.forwarder.portEnv], String(DEV_CODE_AGENT_PROVIDER_CONTRACT.forwarder.port), "cloud-api codex-api forwarder port");
assert.equal(
  cloudApi.env.HWLAB_CODE_AGENT_OPENAI_BASE_URL,
  DEV_CODE_AGENT_PROVIDER_CONTRACT.egress.defaultBaseUrl,
  "cloud-api Code Agent OpenAI base URL must use pod-local Codex API forwarder"
);
assert.equal(
  cloudApi.env[HWLAB_M3_IO_API_BASE_URL_ENV],
  undefined,
  "legacy M3 Skill CLI HWLAB API base URL is removed from default cloud-api config"
);
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_CODEX_STDIO_ENABLED, "1", "cloud-api Codex stdio adapter enabled flag");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_CODEX_STDIO_SUPERVISOR, "repo-owned", "cloud-api Codex stdio supervisor mode");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_WORKSPACE, "/workspace/hwlab", "cloud-api Code Agent workspace contract");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_CODEX_WORKSPACE, "/workspace/hwlab", "cloud-api Codex stdio workspace mount contract");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_CODEX_SANDBOX, "danger-full-access", "cloud-api Codex stdio sandbox contract");
assert.equal(cloudApi.env.HWLAB_CODE_AGENT_CODEX_COMMAND, "/app/node_modules/.bin/codex", "cloud-api Codex command contract");
assert.equal(cloudApi.env.CODEX_HOME, "/codex-home", "cloud-api CODEX_HOME contract");
assertNoProxyIncludes(cloudApi.env.NO_PROXY, DEV_CODE_AGENT_PROVIDER_CONTRACT.noProxyRequired, "cloud-api NO_PROXY contract");
assertNoProxyIncludes(cloudApi.env.no_proxy, DEV_CODE_AGENT_PROVIDER_CONTRACT.noProxyRequired, "cloud-api no_proxy contract");
assert.notEqual(
  cloudApi.env.HWLAB_CODE_AGENT_OPENAI_BASE_URL,
  DEV_CODE_AGENT_PROVIDER_CONTRACT.egress.forbiddenDirectBaseUrl,
  "cloud-api Code Agent OpenAI base URL must not point directly at public api.openai.com"
);
assert.equal(cloudApi.env.OPENAI_API_KEY, codeAgentSecretRefPlaceholder(), "cloud-api Code Agent OpenAI key must be a Secret reference placeholder");
assertCodeAgentProviderWorkloadContract(cloudApiWorkloadEnv);
assertDbForbiddenInvalidHostContract();
assertValidationDoesNotExposeSecretValues(cloudApi.env, cloudApiWorkloadEnv);

console.log(`validated ${schemas.length + deploySchemas.length} JSON files`);

function listItems(document) {
  return document?.kind === "List" ? document.items ?? [] : [document].filter(Boolean);
}

function getWorkloadEnv(workloads, serviceId) {
  const item = getWorkload(workloads, serviceId);
  const container = item?.spec?.template?.spec?.containers?.find((entry) => entry.name === serviceId);
  return Object.fromEntries((container?.env ?? []).map((entry) => [entry.name, entry]));
}

function getWorkload(workloads, serviceId) {
  for (const item of listItems(workloads)) {
    const itemServiceId =
      item?.metadata?.labels?.["hwlab.pikastech.local/service-id"] ||
      item?.spec?.template?.metadata?.labels?.["hwlab.pikastech.local/service-id"] ||
      item?.metadata?.name;
    if (itemServiceId !== serviceId) {
      continue;
    }
    return item;
  }
  return null;
}

function assertCloudApiDbOptionalAlias(services) {
  const alias = DEV_DB_ENV_CONTRACT.dns;
  const service = listItems(services).find((item) => item?.metadata?.name === alias.serviceName);
  assert.equal(DEV_DB_ENV_CONTRACT.endpointAuthority.source, "secret-url-host", "cloud-api DB runtime authority is the Secret URL host");
  assert.equal(DEV_DB_ENV_CONTRACT.endpointAuthority.env, "HWLAB_CLOUD_DB_URL", "cloud-api DB runtime authority env");
  assert.equal(alias.requiredForReadiness, false, "cloud-api DB alias is not a readiness requirement");
  assert.equal(alias.usedForProbe, false, "cloud-api DB alias is not the runtime TCP probe source");
  assert.equal(service, undefined, `Service/${alias.serviceName} is optional until this repo owns endpoints and rollout/apply contract`);
}

function assertCodeAgentProviderWorkloadContract(env) {
  const contract = DEV_CODE_AGENT_PROVIDER_CONTRACT;
  const secretRef = contract.secretRefs[0];
  const apiKey = env[secretRef.env]?.valueFrom?.secretKeyRef;
  assert.equal(env.HWLAB_CODE_AGENT_PROVIDER?.value, contract.codeAgentProvider, "cloud-api workload Code Agent provider");
  assert.equal(env.HWLAB_CODE_AGENT_MODEL?.value, contract.model, "cloud-api workload Code Agent model");
  assert.equal(env.HWLAB_CODE_AGENT_DEFAULT_PROVIDER_PROFILE?.value, contract.profiles.defaultProfile, "cloud-api workload default provider profile");
  assert.equal(env[contract.profiles.deepSeekModelEnv]?.value, "deepseek-chat", "cloud-api workload DeepSeek profile model");
  assert.equal(env[contract.profiles.deepSeekBaseUrlEnv]?.value, contract.profiles.deepSeekBaseUrl, "cloud-api workload DeepSeek profile base URL");
  assert.equal(env[contract.profiles.codexApiModelEnv]?.value, contract.model, "cloud-api workload codex-api profile model");
  assert.equal(env[contract.profiles.codexApiBaseUrlEnv]?.value, contract.egress.defaultBaseUrl, "cloud-api workload codex-api profile base URL must use pod-local forwarder");
  assert.equal(env[contract.forwarder.upstreamEnv]?.value, contract.forwarder.upstreamBaseUrl, "cloud-api workload codex-api upstream must direct-connect to hyueapi");
  assert.equal(env[contract.forwarder.portEnv]?.value, String(contract.forwarder.port), "cloud-api workload codex-api forwarder port");
  assert.equal(
    env.HWLAB_CODE_AGENT_OPENAI_BASE_URL?.value,
    contract.egress.defaultBaseUrl,
    "cloud-api workload Code Agent OpenAI base URL must use pod-local Codex API forwarder"
  );
  assert.equal(
    env[HWLAB_M3_IO_API_BASE_URL_ENV]?.value,
    undefined,
    "legacy M3 Skill CLI HWLAB API base URL is removed from default cloud-api workload"
  );
  assert.equal(env.HWLAB_CODE_AGENT_CODEX_STDIO_ENABLED?.value, "1", "cloud-api workload Codex stdio adapter enabled flag");
  assert.equal(env.HWLAB_CODE_AGENT_CODEX_STDIO_SUPERVISOR?.value, "repo-owned", "cloud-api workload Codex stdio supervisor mode");
  assert.equal(env.HWLAB_CODE_AGENT_WORKSPACE?.value, "/workspace/hwlab", "cloud-api workload Code Agent workspace contract");
  assert.equal(env.HWLAB_CODE_AGENT_CODEX_WORKSPACE?.value, "/workspace/hwlab", "cloud-api workload Codex stdio workspace mount contract");
  assert.equal(env.HWLAB_CODE_AGENT_CODEX_SANDBOX?.value, "danger-full-access", "cloud-api workload Codex stdio sandbox contract");
  assert.equal(env.HWLAB_CODE_AGENT_CODEX_COMMAND?.value, "/app/node_modules/.bin/codex", "cloud-api workload Codex command contract");
  assert.equal(env.CODEX_HOME?.value, "/codex-home", "cloud-api workload CODEX_HOME contract");
  assertNoProxyIncludes(env.NO_PROXY?.value, contract.noProxyRequired, "cloud-api workload NO_PROXY contract");
  assertNoProxyIncludes(env.no_proxy?.value, contract.noProxyRequired, "cloud-api workload no_proxy contract");
  assertCodexHomeMountContract(env, contract);
  assertCodeAgentWorkspaceContract(env, contract);
  assertCodexApiForwarderContract(env, contract);
  assert.notEqual(
    env.HWLAB_CODE_AGENT_OPENAI_BASE_URL?.value,
    contract.egress.forbiddenDirectBaseUrl,
    "cloud-api workload Code Agent OpenAI base URL must not point directly at public api.openai.com"
  );
  assert.equal(apiKey?.name, secretRef.secretName, "cloud-api workload Code Agent OpenAI Secret name");
  assert.equal(apiKey?.key, secretRef.secretKey, "cloud-api workload Code Agent OpenAI Secret key");
}

function assertNoProxyIncludes(value, required, label) {
  const entries = new Set(String(value ?? "")
    .split(/[,;\s]+/u)
    .map((item) => item.trim().toLowerCase())
    .filter(Boolean));
  for (const item of required) {
    assert.equal(entries.has(String(item).toLowerCase()), true, `${label} includes ${item}`);
  }
}

function assertCodexApiForwarderContract(env, contract) {
  const sidecar = (env.__podContainers ?? []).find((entry) => entry.name === contract.forwarder.containerName);
  assert.ok(sidecar, "cloud-api pod includes codex-api loopback forwarder sidecar");
  assert.deepEqual(sidecar.command, contract.forwarder.command, "codex-api forwarder command");
  assert.ok(
    (sidecar.ports ?? []).some((entry) => entry.name === contract.forwarder.portName && entry.containerPort === contract.forwarder.port),
    "codex-api forwarder exposes only Pod-local container port"
  );
  const sidecarEnv = Object.fromEntries((sidecar.env ?? []).map((entry) => [entry.name, entry.value]));
  assert.equal(sidecarEnv[contract.forwarder.listenHostEnv], "127.0.0.1", "codex-api forwarder loopback listen host env");
  assert.equal(sidecarEnv[contract.forwarder.upstreamEnv], contract.forwarder.upstreamBaseUrl, "codex-api forwarder upstream env");
  assert.equal(sidecarEnv[contract.forwarder.portEnv], String(contract.forwarder.port), "codex-api forwarder port env");
  assertNoProxyIncludes(sidecarEnv.NO_PROXY, contract.noProxyRequired, "codex-api forwarder NO_PROXY contract");
  assertNoProxyIncludes(sidecarEnv.no_proxy, contract.noProxyRequired, "codex-api forwarder no_proxy contract");
}

function assertCodexHomeMountContract(env, contract) {
  const volumeMounts = env.__volumeMounts ?? [];
  const volumes = env.__volumes ?? [];
  assert.ok(
    volumeMounts.some((entry) => entry.name === "hwlab-code-agent-codex-home" && entry.mountPath === contract.codexHome.path),
    "cloud-api workload CODEX_HOME writable mount"
  );
  assert.ok(
    volumeMounts.some((entry) =>
      entry.name === "hwlab-code-agent-codex-config" &&
      entry.mountPath === `${contract.codexHome.path}/${contract.codexHome.configKey}` &&
      entry.subPath === contract.codexHome.configKey &&
      entry.readOnly === true
    ),
    "cloud-api workload Codex config.toml read-only mount"
  );
  assert.ok(
    volumeMounts.some((entry) =>
      entry.name === "hwlab-code-agent-codex-auth" &&
      entry.mountPath === `${contract.codexHome.path}/${contract.codexHome.authKey}` &&
      entry.subPath === contract.codexHome.authKey &&
      entry.readOnly === true
    ),
    "cloud-api workload Codex auth.json read-only mount"
  );
  assert.ok(
    volumes.some((entry) =>
      entry.name === "hwlab-code-agent-codex-config" &&
      entry.configMap?.name === contract.codexHome.configMapName &&
      (entry.configMap.items ?? []).some((item) => item.key === contract.codexHome.configKey && item.path === contract.codexHome.configKey)
    ),
    "cloud-api workload Codex config ConfigMap ref"
  );
  assert.ok(
    volumes.some((entry) =>
      entry.name === "hwlab-code-agent-codex-auth" &&
      entry.secret?.secretName === contract.codexHome.secretName &&
      (entry.secret.items ?? []).some((item) => item.key === contract.codexHome.authKey && item.path === contract.codexHome.authKey)
    ),
    "cloud-api workload Codex auth Secret ref"
  );
}

function assertCodeAgentWorkspaceContract(env, contract) {
  const workspace = contract.workspace;
  const volumeMounts = env.__volumeMounts ?? [];
  const volumes = env.__volumes ?? [];
  const initContainers = env.__initContainers ?? [];
  const pvc = env.__workspacePvc;
  assert.ok(
    volumeMounts.some((entry) => entry.name === workspace.volumeName && entry.mountPath === workspace.mountPath && entry.readOnly !== true),
    "cloud-api workload Code Agent workspace writable mount"
  );
  assert.ok(
    volumes.some((entry) => entry.name === workspace.volumeName && entry.persistentVolumeClaim?.claimName === workspace.claimName),
    "cloud-api workload Code Agent workspace PVC volume"
  );
  assert.equal(pvc?.kind, "PersistentVolumeClaim", "Code Agent workspace PVC resource");
  assert.equal(pvc?.metadata?.name, workspace.claimName, "Code Agent workspace PVC name");
  assert.ok((pvc?.spec?.accessModes ?? []).includes(workspace.accessMode), "Code Agent workspace PVC uses ReadWriteOnce");
  assert.equal(pvc?.spec?.resources?.requests?.storage, workspace.storage, "Code Agent workspace PVC requested storage");
  const initContainer = initContainers.find((entry) => entry.name === workspace.initContainerName);
  assert.ok(initContainer, "cloud-api workload initializes persistent Code Agent workspace");
  assert.ok(
    (initContainer?.volumeMounts ?? []).some((entry) => entry.name === workspace.volumeName && entry.mountPath === workspace.mountPath),
    "Code Agent workspace init container mounts the persistent workspace"
  );
  const initCommand = [...(initContainer?.command ?? []), ...(initContainer?.args ?? [])].join("\n");
  assert.ok(
    initCommand.includes(workspace.sourcePath) && initCommand.includes(workspace.path) && initCommand.includes(workspace.initMarker),
    "Code Agent workspace init container uses copy-once /app bootstrap"
  );
  assert.equal(env.__deploymentStrategy?.type, workspace.rolloutStrategy, "cloud-api uses Recreate rollout for single-writer workspace PVC");
}

function assertDbForbiddenInvalidHostContract() {
  const invalidHost = parseDbUrlContract("postgres://user:password@hwlab-dev-db.invalid:5432/hwlab");
  assert.equal(invalidHost.ok, false, "DEV DB contract must reject .invalid runtime hosts");
  assert.equal(invalidHost.result, "forbidden_runtime_host", "DEV DB invalid host result");
  assert.equal(invalidHost.classification, "db_url_forbidden_invalid_host", "DEV DB invalid host classification");
}

function assertValidationDoesNotExposeSecretValues(manifestEnv, workloadEnv) {
  const serialized = JSON.stringify({ manifestEnv, workloadEnv });
  assert.equal(/sk-[A-Za-z0-9._-]{16,}/u.test(serialized), false, "validation contract must not include OpenAI key material");
  assert.equal(/postgres:\/\/[^" ]+:[^" ]+@/u.test(serialized), false, "validation contract must not include DB URL credentials");
}
