import { readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { DEV_DB_ENV_CONTRACT } 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 { readStructuredFile } from "./structured-config.mjs";

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const expectedPorts = Object.freeze({ frontend: 16666, api: 16667 });
const codeAgentBackendTimeoutMs = "1200000";
const codeAgentTransportTimeoutMs = "1260000";
const legacyPublicPorts = new Set([6666, 6667]);
const tomlBareKeyPattern = /^[A-Za-z0-9_-]+$/u;

function parseArgs(argv) {
  const args = { check: false, pretty: false };
  for (const arg of argv) {
    if (arg === "--check") {
      args.check = true;
    } else if (arg === "--pretty") {
      args.pretty = true;
    } else {
      throw new Error(`unknown argument: ${arg}`);
    }
  }
  return args;
}

async function readJson(relativePath) {
  return readStructuredFile(repoRoot, relativePath);
}

function stripTomlComment(line) {
  let inString = false;
  let escaped = false;
  for (let index = 0; index < line.length; index += 1) {
    const char = line[index];
    if (inString) {
      if (escaped) {
        escaped = false;
      } else if (char === "\\") {
        escaped = true;
      } else if (char === "\"") {
        inString = false;
      }
    } else if (char === "\"") {
      inString = true;
    } else if (char === "#") {
      return line.slice(0, index);
    }
  }
  return line;
}

function parseTomlValue(value, relativePath, lineNumber) {
  if (value.startsWith("\"")) {
    try {
      const parsed = JSON.parse(value);
      if (typeof parsed !== "string") {
        throw new Error("not a string");
      }
      return parsed;
    } catch {
      throw new Error(`${relativePath}:${lineNumber}: invalid TOML basic string`);
    }
  }
  if (value === "true") return true;
  if (value === "false") return false;
  if (/^[+-]?\d(?:_?\d)*$/u.test(value)) {
    return Number.parseInt(value.replaceAll("_", ""), 10);
  }
  throw new Error(`${relativePath}:${lineNumber}: unsupported TOML value ${JSON.stringify(value)}`);
}

// Keep this parser scoped to the FRP TOML subset used in this repo so the dry-run
// contract check does not depend on Python 3.11's tomllib being present.
export function parseFrpTomlText(text, relativePath = "FRP TOML") {
  const document = {};
  let current = document;
  for (const [lineIndex, rawLine] of text.split(/\r?\n/u).entries()) {
    const lineNumber = lineIndex + 1;
    const line = stripTomlComment(rawLine).trim();
    if (line === "") continue;

    const arrayTableMatch = line.match(/^\[\[([A-Za-z0-9_-]+)\]\]$/u);
    if (arrayTableMatch) {
      const name = arrayTableMatch[1];
      if (!Array.isArray(document[name])) {
        if (Object.hasOwn(document, name)) {
          throw new Error(`${relativePath}:${lineNumber}: cannot redefine scalar ${name} as array table`);
        }
        document[name] = [];
      }
      current = {};
      document[name].push(current);
      continue;
    }

    if (line.startsWith("[") || line.includes("]")) {
      throw new Error(`${relativePath}:${lineNumber}: only root keys and array-of-table headers are supported`);
    }

    const assignmentMatch = line.match(/^([A-Za-z0-9_-]+)\s*=\s*(.+)$/u);
    if (!assignmentMatch) {
      throw new Error(`${relativePath}:${lineNumber}: expected key = value`);
    }
    const [, key, valueSource] = assignmentMatch;
    if (!tomlBareKeyPattern.test(key)) {
      throw new Error(`${relativePath}:${lineNumber}: unsupported TOML key ${JSON.stringify(key)}`);
    }
    if (Object.hasOwn(current, key)) {
      throw new Error(`${relativePath}:${lineNumber}: duplicate TOML key ${key}`);
    }
    current[key] = parseTomlValue(valueSource.trim(), relativePath, lineNumber);
  }
  return document;
}

async function parseToml(relativePath) {
  return parseFrpTomlText(await readFile(path.join(repoRoot, relativePath), "utf8"), relativePath);
}

function addDiagnostic(ctx, code, jsonPath, message, { expected, actual } = {}) {
  ctx.diagnostics.push({
    code,
    path: jsonPath,
    message,
    ...(expected === undefined ? {} : { expected }),
    ...(actual === undefined ? {} : { actual })
  });
}

function expect(ctx, condition, code, jsonPath, message, details) {
  ctx.checks += 1;
  if (!condition) {
    addDiagnostic(ctx, code, jsonPath, message, details);
  }
}

function expectEqual(ctx, actual, expected, jsonPath, message) {
  expect(ctx, Object.is(actual, expected), "contract_mismatch", jsonPath, message, { expected, actual });
}

function flagLegacyPublicPort(ctx, jsonPath, actual, expected, label) {
  if (legacyPublicPorts.has(Number(actual))) {
    addDiagnostic(ctx, "legacy_public_endpoint_drift", jsonPath, `${label} uses legacy public port ${actual}`, {
      expected,
      actual
    });
    return;
  }
  expectEqual(ctx, Number(actual), expected, jsonPath, `${label} public port`);
}

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

function mapByServiceId(items) {
  return new Map(
    items.map((item) => [
      item?.metadata?.labels?.["hwlab.pikastech.local/service-id"] ?? item?.metadata?.name,
      item
    ])
  );
}

function mapByName(items) {
  return new Map(items.map((item) => [item?.metadata?.name, item]));
}

function parseEndpoint(ctx, id, endpoint) {
  const expectedPort = expectedPorts[id];
  expect(ctx, Boolean(endpoint), "missing_source", `$.publicEndpoints.${id}`, `${id} public endpoint is required`);
  if (!endpoint) return null;

  let urlPort = null;
  try {
    const url = new URL(endpoint.url);
    urlPort = Number(url.port || (url.protocol === "http:" ? 80 : 443));
    expectEqual(ctx, url.protocol.replace(":", ""), endpoint.protocol, `$.publicEndpoints.${id}.url`, `${id} URL protocol`);
    expectEqual(ctx, url.hostname, endpoint.host, `$.publicEndpoints.${id}.url`, `${id} URL host`);
  } catch (error) {
    addDiagnostic(ctx, "invalid_url", `$.publicEndpoints.${id}.url`, `${id} public endpoint URL is invalid`, {
      actual: endpoint.url
    });
  }

  expectEqual(ctx, endpoint.protocol, "http", `$.publicEndpoints.${id}.protocol`, `${id} public endpoint protocol`);
  expectEqual(ctx, endpoint.host, "74.48.78.17", `$.publicEndpoints.${id}.host`, `${id} public endpoint host`);
  flagLegacyPublicPort(ctx, `$.publicEndpoints.${id}.port`, endpoint.port, expectedPort, `${id} endpoint`);
  if (urlPort !== null) {
    flagLegacyPublicPort(ctx, `$.publicEndpoints.${id}.url`, urlPort, expectedPort, `${id} endpoint URL`);
  }
  return { endpointId: id, ...endpoint };
}

function validateSource(ctx, manifest) {
  expectEqual(ctx, manifest.environment, "dev", "$.environment", "manifest environment");
  expectEqual(ctx, manifest.profiles?.prod?.enabled, false, "$.profiles.prod.enabled", "PROD profile must stay disabled");
  expectEqual(ctx, manifest.health?.method, "GET", "$.health.method", "health method");
  expectEqual(ctx, manifest.health?.path, "/health/live", "$.health.path", "health path");
  expectEqual(ctx, manifest.health?.responseFormat, "json", "$.health.responseFormat", "health response format");

  const services = manifest.services ?? [];
  const servicesById = new Map(services.map((service) => [service.serviceId, service]));
  for (const service of services) {
    expectEqual(ctx, service.healthPath, manifest.health?.path, `$.services.${service.serviceId}.healthPath`, `${service.serviceId} health path`);
  }

  const endpoints = {
    frontend: parseEndpoint(ctx, "frontend", manifest.publicEndpoints?.frontend),
    api: parseEndpoint(ctx, "api", manifest.publicEndpoints?.api)
  };
  for (const [id, endpoint] of Object.entries(endpoints)) {
    expect(ctx, servicesById.has(endpoint?.serviceId), "unknown_service", `$.publicEndpoints.${id}.serviceId`, `${id} public endpoint service must exist`);
  }
  expectEqual(ctx, manifest.endpoint, endpoints.api?.url, "$.endpoint", "legacy manifest endpoint alias must point to API endpoint");
  expectEqual(ctx, manifest.profiles?.dev?.endpoint, endpoints.api?.url, "$.profiles.dev.endpoint", "DEV profile endpoint");

  const cloudApi = servicesById.get("hwlab-cloud-api");
  const cloudWeb = servicesById.get("hwlab-cloud-web");
  const edgeProxy = servicesById.get("hwlab-edge-proxy");
  expectEqual(ctx, cloudApi?.env?.HWLAB_PUBLIC_ENDPOINT, endpoints.api?.url, "$.services.hwlab-cloud-api.env.HWLAB_PUBLIC_ENDPOINT", "cloud API public endpoint env");
  validateCloudApiDbSource(ctx, cloudApi?.env ?? {});
  validateCloudApiCodeAgentSource(ctx, cloudApi?.env ?? {});
  validateCodeAgentProxyTimeoutSource(ctx, { cloudApi, cloudWeb, edgeProxy });

  const proxies = manifest.frp?.proxies ?? [];
  const proxyNames = new Set();
  for (const [index, proxy] of proxies.entries()) {
    const basePath = `$.frp.proxies[${index}]`;
    expect(ctx, !proxyNames.has(proxy.name), "duplicate_source", `${basePath}.name`, `duplicate frp proxy ${proxy.name}`);
    proxyNames.add(proxy.name);
    expectEqual(ctx, proxy.type, "tcp", `${basePath}.type`, `${proxy.name} proxy type`);
    expectEqual(ctx, proxy.localHost, `${proxy.localServiceId}.${manifest.namespace}.svc.cluster.local`, `${basePath}.localHost`, `${proxy.name} local host`);
    if (proxy.endpointId) {
      const endpoint = endpoints[proxy.endpointId];
      expectEqual(ctx, endpoint?.frpProxy, proxy.name, `${basePath}.name`, `${proxy.endpointId} endpoint frp proxy`);
      flagLegacyPublicPort(ctx, `${basePath}.remotePort`, proxy.remotePort, endpoint?.port, `${proxy.name} remote`);
    }
  }

  const serviceMappings = manifest.k3s?.serviceMappings ?? [];
  const mappingIds = new Set();
  const mappingNames = new Set();
  for (const [index, mapping] of serviceMappings.entries()) {
    const basePath = `$.k3s.serviceMappings[${index}]`;
    expect(ctx, servicesById.has(mapping.serviceId), "unknown_service", `${basePath}.serviceId`, `${mapping.serviceId} must exist in services`);
    expect(ctx, !mappingNames.has(mapping.name), "duplicate_source", `${basePath}.name`, `duplicate k3s mapping name ${mapping.name}`);
    mappingNames.add(mapping.name);
    expect(
      ctx,
      !mappingIds.has(mapping.serviceId),
      "duplicate_source",
      `${basePath}.serviceId`,
      `duplicate k3s mapping ${mapping.serviceId}`
    );
    mappingIds.add(mapping.serviceId);
    expectEqual(ctx, mapping.namespace, manifest.namespace, `${basePath}.namespace`, `${mapping.serviceId} namespace`);
    expectEqual(ctx, mapping.targetPort, "http", `${basePath}.targetPort`, `${mapping.serviceId} targetPort`);
  }

  return { manifest, endpoints, servicesById, proxies, serviceMappings, healthPath: manifest.health?.path };
}

function validateCloudApiDbSource(ctx, env) {
  const alias = DEV_DB_ENV_CONTRACT.dns;
  expectEqual(ctx, env.HWLAB_CLOUD_DB_URL, "secretRef:hwlab-cloud-api-dev-db/database-url", "$.services.hwlab-cloud-api.env.HWLAB_CLOUD_DB_URL", "cloud API DB URL Secret reference");
  expectEqual(
    ctx,
    env.HWLAB_CLOUD_DB_SSL_MODE,
    DEV_DB_ENV_CONTRACT.nonSecretDefaults.HWLAB_CLOUD_DB_SSL_MODE,
    "$.services.hwlab-cloud-api.env.HWLAB_CLOUD_DB_SSL_MODE",
    "cloud API DEV DB SSL mode"
  );
  expectEqual(ctx, env.HWLAB_CLOUD_DB_CONTRACT, "dev-redacted-presence-only", "$.services.hwlab-cloud-api.env.HWLAB_CLOUD_DB_CONTRACT", "cloud API DB redacted contract marker");
  expectEqual(ctx, DEV_DB_ENV_CONTRACT.endpointAuthority.source, "secret-url-host", "internal/cloud/db-contract.ts.endpointAuthority.source", "cloud API DB runtime authority source");
  expectEqual(ctx, DEV_DB_ENV_CONTRACT.endpointAuthority.env, "HWLAB_CLOUD_DB_URL", "internal/cloud/db-contract.ts.endpointAuthority.env", "cloud API DB runtime authority env");
  expectEqual(ctx, alias.requiredForReadiness, false, "internal/cloud/db-contract.ts.dns.requiredForReadiness", "cloud API DB DNS alias readiness requirement");
  expectEqual(ctx, alias.usedForProbe, false, "internal/cloud/db-contract.ts.dns.usedForProbe", "cloud API DB DNS alias probe source");
  for (const name of [
    "HWLAB_CLOUD_DB_SERVICE_NAME",
    "HWLAB_CLOUD_DB_SERVICE_NAMESPACE",
    "HWLAB_CLOUD_DB_HOST",
    "HWLAB_CLOUD_DB_PORT"
  ]) {
    expectEqual(ctx, env[name], undefined, `$.services.hwlab-cloud-api.env.${name}`, `${name} is optional and not a readiness hard requirement`);
  }
}

function validateCloudApiCodeAgentSource(ctx, env) {
  const contract = DEV_CODE_AGENT_PROVIDER_CONTRACT;
  expectEqual(ctx, env.HWLAB_CODE_AGENT_PROVIDER, contract.codeAgentProvider, "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_PROVIDER", "cloud API Code Agent provider");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_MODEL, contract.model, "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_MODEL", "cloud API Code Agent model");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_DEFAULT_PROVIDER_PROFILE, contract.profiles.defaultProfile, "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_DEFAULT_PROVIDER_PROFILE", "cloud API default provider profile");
  expectEqual(ctx, env[contract.profiles.deepSeekModelEnv], "deepseek-chat", `$.services.hwlab-cloud-api.env.${contract.profiles.deepSeekModelEnv}`, "cloud API DeepSeek profile model");
  expectEqual(ctx, env[contract.profiles.deepSeekBaseUrlEnv], contract.profiles.deepSeekBaseUrl, `$.services.hwlab-cloud-api.env.${contract.profiles.deepSeekBaseUrlEnv}`, "cloud API DeepSeek profile base URL");
  expectEqual(ctx, env[contract.profiles.codexApiModelEnv], contract.model, `$.services.hwlab-cloud-api.env.${contract.profiles.codexApiModelEnv}`, "cloud API codex-api profile model");
  expectEqual(ctx, env[contract.profiles.codexApiBaseUrlEnv], contract.egress.defaultBaseUrl, `$.services.hwlab-cloud-api.env.${contract.profiles.codexApiBaseUrlEnv}`, "cloud API codex-api profile base URL");
  expectEqual(ctx, env[contract.forwarder.upstreamEnv], contract.forwarder.upstreamBaseUrl, `$.services.hwlab-cloud-api.env.${contract.forwarder.upstreamEnv}`, "cloud API codex-api upstream base URL");
  expectEqual(ctx, env[contract.forwarder.portEnv], String(contract.forwarder.port), `$.services.hwlab-cloud-api.env.${contract.forwarder.portEnv}`, "cloud API codex-api forwarder port");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_TIMEOUT_MS, codeAgentBackendTimeoutMs, "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_TIMEOUT_MS", "cloud API Code Agent hard timeout budget");
  expectEqual(
    ctx,
    env.HWLAB_CODE_AGENT_OPENAI_BASE_URL,
    contract.egress.defaultBaseUrl,
    "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_OPENAI_BASE_URL",
    "cloud API Code Agent pod-local Codex API forwarder base URL"
  );
  expectEqual(
    ctx,
    env[HWLAB_M3_IO_API_BASE_URL_ENV],
    undefined,
    `$.services.hwlab-cloud-api.env.${HWLAB_M3_IO_API_BASE_URL_ENV}`,
    "legacy M3 Skill CLI HWLAB API base URL is removed from default cloud-api config"
  );
  expectEqual(ctx, env.HWLAB_CODE_AGENT_CODEX_STDIO_ENABLED, "1", "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_STDIO_ENABLED", "cloud API Codex stdio adapter enabled flag");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_CODEX_STDIO_SUPERVISOR, "repo-owned", "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_STDIO_SUPERVISOR", "cloud API Codex stdio supervisor mode");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_WORKSPACE, "/workspace/hwlab", "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_WORKSPACE", "cloud API Code Agent workspace contract");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_CODEX_WORKSPACE, "/workspace/hwlab", "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_WORKSPACE", "cloud API Codex stdio workspace mount contract");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_CODEX_SANDBOX, "danger-full-access", "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_SANDBOX", "cloud API Codex stdio sandbox contract");
  expectEqual(ctx, env.HWLAB_CODE_AGENT_CODEX_COMMAND, "/app/node_modules/.bin/codex", "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_COMMAND", "cloud API Codex command contract");
  expectEqual(ctx, env.CODEX_HOME, "/codex-home", "$.services.hwlab-cloud-api.env.CODEX_HOME", "cloud API CODEX_HOME contract");
  expectNoProxyIncludes(ctx, env.NO_PROXY, contract.noProxyRequired, "$.services.hwlab-cloud-api.env.NO_PROXY");
  expectNoProxyIncludes(ctx, env.no_proxy, contract.noProxyRequired, "$.services.hwlab-cloud-api.env.no_proxy");
  expect(
    ctx,
    env.HWLAB_CODE_AGENT_OPENAI_BASE_URL !== contract.egress.forbiddenDirectBaseUrl,
    "forbidden_direct_egress",
    "$.services.hwlab-cloud-api.env.HWLAB_CODE_AGENT_OPENAI_BASE_URL",
    "cloud API Code Agent must not point directly at public api.openai.com",
    { expected: contract.egress.target, actual: env.HWLAB_CODE_AGENT_OPENAI_BASE_URL }
  );
  expectEqual(ctx, env.OPENAI_API_KEY, codeAgentSecretRefPlaceholder(), "$.services.hwlab-cloud-api.env.OPENAI_API_KEY", "cloud API Code Agent OpenAI Secret reference");
}

function validateCodeAgentProxyTimeoutSource(ctx, { cloudApi, cloudWeb, edgeProxy }) {
  expectEqual(ctx, cloudWeb?.env?.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS, codeAgentTransportTimeoutMs, "$.services.hwlab-cloud-web.env.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS", "Cloud Web same-origin Code Agent proxy timeout budget");
  expectEqual(ctx, edgeProxy?.env?.HWLAB_EDGE_PROXY_TIMEOUT_MS, codeAgentTransportTimeoutMs, "$.services.hwlab-edge-proxy.env.HWLAB_EDGE_PROXY_TIMEOUT_MS", "edge proxy Code Agent timeout budget");
  const backendTimeoutMs = cloudApi?.env?.HWLAB_CODE_AGENT_TIMEOUT_MS;
  expect(
    ctx,
    Number.parseInt(cloudWeb?.env?.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS ?? "0", 10) > Number.parseInt(backendTimeoutMs ?? "0", 10),
    "code_agent_timeout_layering",
    "$.services.hwlab-cloud-web.env.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS",
    "Cloud Web proxy must wait longer than cloud-api so structured Code Agent timeout wins",
    { expected: `>${backendTimeoutMs}`, actual: cloudWeb?.env?.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS }
  );
  expect(
    ctx,
    Number.parseInt(edgeProxy?.env?.HWLAB_EDGE_PROXY_TIMEOUT_MS ?? "0", 10) > Number.parseInt(backendTimeoutMs ?? "0", 10),
    "code_agent_timeout_layering",
    "$.services.hwlab-edge-proxy.env.HWLAB_EDGE_PROXY_TIMEOUT_MS",
    "Edge proxy must wait longer than cloud-api so structured Code Agent timeout wins",
    { expected: `>${backendTimeoutMs}`, actual: edgeProxy?.env?.HWLAB_EDGE_PROXY_TIMEOUT_MS }
  );
}

function renderPlan(source) {
  const proxyPorts = [...new Set(source.proxies.map((proxy) => Number(proxy.remotePort)))].sort((a, b) => a - b);
  return {
    publicEndpoints: Object.fromEntries(
      Object.entries(source.endpoints).map(([id, endpoint]) => [id, {
        url: endpoint?.url,
        serviceId: endpoint?.serviceId,
        port: endpoint?.port,
        frpProxy: endpoint?.frpProxy
      }])
    ),
    frpc: {
      serverAddr: source.manifest.frp?.server?.address,
      serverPort: source.manifest.frp?.server?.bindPort,
      proxies: source.proxies.map((proxy) => ({
        name: proxy.name,
        type: proxy.type,
        localIP: proxy.localHost,
        localPort: proxy.localPort,
        remotePort: proxy.remotePort
      }))
    },
    frps: {
      bindPort: source.manifest.frp?.server?.bindPort,
      allowPorts: proxyPorts.map((port) => ({ start: port, end: port }))
    },
    k3sServices: source.serviceMappings.map((mapping) => ({
      name: mapping.name,
      namespace: mapping.namespace,
      serviceId: mapping.serviceId,
      port: mapping.port,
      targetPort: mapping.targetPort
    })),
    health: {
      method: source.manifest.health?.method,
      path: source.healthPath,
      endpoint: source.endpoints.api?.url
    }
  };
}

function validateFrpArtifacts(ctx, source, rendered, frpc, frps) {
  expectEqual(ctx, frpc.serverAddr, rendered.frpc.serverAddr, "deploy/frp/frpc.dev.toml.serverAddr", "frpc server address");
  expectEqual(ctx, frpc.serverPort, rendered.frpc.serverPort, "deploy/frp/frpc.dev.toml.serverPort", "frpc server port");
  const actualProxies = new Map((frpc.proxies ?? []).map((proxy) => [proxy.name, proxy]));
  for (const proxy of source.proxies) {
    const actual = actualProxies.get(proxy.name);
    expect(ctx, Boolean(actual), "missing_rendered_artifact", `deploy/frp/frpc.dev.toml.${proxy.name}`, `${proxy.name} proxy exists`);
    if (!actual) continue;
    expectEqual(ctx, actual.type, proxy.type, `deploy/frp/frpc.dev.toml.${proxy.name}.type`, `${proxy.name} type`);
    expectEqual(ctx, actual.localIP, proxy.localHost, `deploy/frp/frpc.dev.toml.${proxy.name}.localIP`, `${proxy.name} local IP`);
    expectEqual(ctx, actual.localPort, proxy.localPort, `deploy/frp/frpc.dev.toml.${proxy.name}.localPort`, `${proxy.name} local port`);
    if (proxy.endpointId) {
      flagLegacyPublicPort(ctx, `deploy/frp/frpc.dev.toml.${proxy.name}.remotePort`, actual.remotePort, source.endpoints[proxy.endpointId]?.port, `${proxy.name} rendered remote`);
    } else {
      expectEqual(ctx, actual.remotePort, proxy.remotePort, `deploy/frp/frpc.dev.toml.${proxy.name}.remotePort`, `${proxy.name} remote port`);
    }
  }

  expectEqual(ctx, frps.bindPort, rendered.frps.bindPort, "deploy/frp/frps.dev.toml.bindPort", "frps bind port");
  for (const allow of rendered.frps.allowPorts) {
    const match = (frps.allowPorts ?? []).some((actual) => actual.start === allow.start && actual.end === allow.end);
    expect(ctx, match, "missing_rendered_artifact", `deploy/frp/frps.dev.toml.allowPorts.${allow.start}`, `frps allows remote port ${allow.start}`);
  }
  for (const [index, allow] of (frps.allowPorts ?? []).entries()) {
    for (const legacyPort of legacyPublicPorts) {
      if (allow.start <= legacyPort && allow.end >= legacyPort) {
        addDiagnostic(ctx, "legacy_public_endpoint_drift", `deploy/frp/frps.dev.toml.allowPorts[${index}]`, `frps allows legacy public port ${legacyPort}`, {
          expected: [expectedPorts.frontend, expectedPorts.api],
          actual: { start: allow.start, end: allow.end }
        });
      }
    }
  }
}

function validateK3sArtifacts(ctx, source, rendered, services, workloads, healthContract, masterEdge) {
  const serviceItems = mapByName(listItems(services));
  const workloadItems = mapByServiceId(listItems(workloads));
  for (const expected of rendered.k3sServices) {
    const actual = serviceItems.get(expected.name);
    expect(ctx, Boolean(actual), "missing_rendered_artifact", `deploy/k8s/base/services.yaml.${expected.serviceId}`, `${expected.serviceId} k3s service exists`);
    if (actual) {
      const port = (actual.spec?.ports ?? []).find((entry) => entry.name === "http") ?? actual.spec?.ports?.[0];
      expectEqual(ctx, actual.metadata?.name, expected.name, `deploy/k8s/base/services.yaml.${expected.serviceId}.metadata.name`, `${expected.serviceId} service name`);
      expectEqual(ctx, actual.metadata?.namespace, expected.namespace, `deploy/k8s/base/services.yaml.${expected.serviceId}.metadata.namespace`, `${expected.serviceId} service namespace`);
      expectEqual(ctx, port?.port, expected.port, `deploy/k8s/base/services.yaml.${expected.serviceId}.spec.ports.http.port`, `${expected.serviceId} service port`);
      expectEqual(ctx, port?.targetPort, expected.targetPort, `deploy/k8s/base/services.yaml.${expected.serviceId}.spec.ports.http.targetPort`, `${expected.serviceId} service targetPort`);
    }
    const container = workloadItems.get(expected.serviceId)?.spec?.template?.spec?.containers?.[0];
    for (const probeName of ["readinessProbe", "livenessProbe"]) {
      if (container?.[probeName]?.httpGet?.path) {
        expectEqual(ctx, container[probeName].httpGet.path, source.healthPath, `deploy/k8s/base/workloads.yaml.${expected.serviceId}.${probeName}`, `${expected.serviceId} ${probeName} path`);
      }
    }
  }

  validateCloudApiDbOptionalAliasArtifacts(ctx, services, workloads);
  validateCloudApiCodeAgentArtifacts(ctx, workloads);
  validateCodeAgentProxyTimeoutArtifacts(ctx, workloads);

  expectEqual(ctx, healthContract.data?.endpoint, source.endpoints.api?.url, "deploy/k8s/dev/health-contract.yaml.data.endpoint", "health contract endpoint");
  expectEqual(ctx, masterEdge.endpoint, source.endpoints.api?.url, "deploy/master-edge/health-contract.json.endpoint", "master edge endpoint");
  flagLegacyPublicPort(ctx, "deploy/master-edge/health-contract.json.reverseLink.publicPort", masterEdge.reverseLink?.publicPort, expectedPorts.api, "master edge API");
  flagLegacyPublicPort(ctx, "deploy/master-edge/health-contract.json.reverseLink.webPublicPort", masterEdge.reverseLink?.webPublicPort, expectedPorts.frontend, "master edge frontend");
  expectEqual(ctx, masterEdge.reverseLink?.direction, "edge-proxy-only", "deploy/master-edge/health-contract.json.reverseLink.direction", "master edge reverse link no longer models a tunnel-client service");
  expectEqual(ctx, masterEdge.reverseLink?.client, undefined, "deploy/master-edge/health-contract.json.reverseLink.client", "master edge reverse link does not name removed tunnel-client");
  expectEqual(ctx, masterEdge.prodAcceptance, false, "deploy/master-edge/health-contract.json.prodAcceptance", "master edge PROD acceptance");
}

function validateCloudApiDbOptionalAliasArtifacts(ctx, services, workloads) {
  const alias = DEV_DB_ENV_CONTRACT.dns;
  const service = listItems(services).find((item) => item?.metadata?.name === alias.serviceName);
  expectEqual(ctx, service, undefined, "deploy/k8s/base/services.yaml.cloud-api-db", "cloud-api-db remains optional until Service/Endpoint ownership and rollout contract exist");
  const container = mapByServiceId(listItems(workloads)).get("hwlab-cloud-api")?.spec?.template?.spec?.containers?.[0];
  const env = new Map((container?.env ?? []).map((entry) => [entry.name, entry.value]));
  expectEqual(
    ctx,
    env.get("HWLAB_CLOUD_DB_SSL_MODE"),
    DEV_DB_ENV_CONTRACT.nonSecretDefaults.HWLAB_CLOUD_DB_SSL_MODE,
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CLOUD_DB_SSL_MODE",
    "cloud API workload DEV DB SSL mode"
  );
  for (const name of [
    "HWLAB_CLOUD_DB_SERVICE_NAME",
    "HWLAB_CLOUD_DB_SERVICE_NAMESPACE",
    "HWLAB_CLOUD_DB_HOST",
    "HWLAB_CLOUD_DB_PORT"
  ]) {
    expectEqual(ctx, env.get(name), undefined, `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${name}`, `${name} is optional and not injected as readiness authority`);
  }
}

function validateCloudApiCodeAgentArtifacts(ctx, workloads) {
  const contract = DEV_CODE_AGENT_PROVIDER_CONTRACT;
  const secretRef = contract.secretRefs[0];
  const workloadItems = mapByServiceId(listItems(workloads));
  const workload = workloadItems.get("hwlab-cloud-api");
  const templateSpec = workload?.spec?.template?.spec ?? {};
  const container = templateSpec.containers?.[0];
  const env = new Map((container?.env ?? []).map((entry) => [entry.name, entry]));
  const podContainers = templateSpec.containers ?? [];
  const initContainers = templateSpec.initContainers ?? [];
  const volumes = templateSpec.volumes ?? [];
  const workspacePvc = workloadItems.get(contract.workspace.claimName);
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_PROVIDER")?.value, contract.codeAgentProvider, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_PROVIDER", "cloud API workload Code Agent provider");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_MODEL")?.value, contract.model, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_MODEL", "cloud API workload Code Agent model");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_DEFAULT_PROVIDER_PROFILE")?.value, contract.profiles.defaultProfile, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_DEFAULT_PROVIDER_PROFILE", "cloud API workload default provider profile");
  expectEqual(ctx, env.get(contract.profiles.deepSeekModelEnv)?.value, "deepseek-chat", `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${contract.profiles.deepSeekModelEnv}`, "cloud API workload DeepSeek profile model");
  expectEqual(ctx, env.get(contract.profiles.deepSeekBaseUrlEnv)?.value, contract.profiles.deepSeekBaseUrl, `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${contract.profiles.deepSeekBaseUrlEnv}`, "cloud API workload DeepSeek profile base URL");
  expectEqual(ctx, env.get(contract.profiles.codexApiModelEnv)?.value, contract.model, `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${contract.profiles.codexApiModelEnv}`, "cloud API workload codex-api profile model");
  expectEqual(ctx, env.get(contract.profiles.codexApiBaseUrlEnv)?.value, contract.egress.defaultBaseUrl, `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${contract.profiles.codexApiBaseUrlEnv}`, "cloud API workload codex-api profile base URL");
  expectEqual(ctx, env.get(contract.forwarder.upstreamEnv)?.value, contract.forwarder.upstreamBaseUrl, `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${contract.forwarder.upstreamEnv}`, "cloud API workload codex-api upstream base URL");
  expectEqual(ctx, env.get(contract.forwarder.portEnv)?.value, String(contract.forwarder.port), `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${contract.forwarder.portEnv}`, "cloud API workload codex-api forwarder port");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_TIMEOUT_MS")?.value, codeAgentBackendTimeoutMs, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_TIMEOUT_MS", "cloud API workload Code Agent hard timeout budget");
  expectEqual(
    ctx,
    env.get("HWLAB_CODE_AGENT_OPENAI_BASE_URL")?.value,
    contract.egress.defaultBaseUrl,
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_OPENAI_BASE_URL",
    "cloud API workload Code Agent pod-local Codex API forwarder base URL"
  );
  expectEqual(
    ctx,
    env.get(HWLAB_M3_IO_API_BASE_URL_ENV)?.value,
    undefined,
    `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.${HWLAB_M3_IO_API_BASE_URL_ENV}`,
    "legacy M3 Skill CLI HWLAB API base URL is removed from default cloud-api workload"
  );
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_CODEX_STDIO_ENABLED")?.value, "1", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_STDIO_ENABLED", "cloud API workload Codex stdio adapter enabled flag");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_CODEX_STDIO_SUPERVISOR")?.value, "repo-owned", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_STDIO_SUPERVISOR", "cloud API workload Codex stdio supervisor mode");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_WORKSPACE")?.value, "/workspace/hwlab", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_WORKSPACE", "cloud API workload Code Agent workspace contract");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_CODEX_WORKSPACE")?.value, "/workspace/hwlab", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_WORKSPACE", "cloud API workload Codex stdio workspace mount contract");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_CODEX_SANDBOX")?.value, "danger-full-access", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_SANDBOX", "cloud API workload Codex stdio sandbox contract");
  expectEqual(ctx, env.get("HWLAB_CODE_AGENT_CODEX_COMMAND")?.value, "/app/node_modules/.bin/codex", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_CODEX_COMMAND", "cloud API workload Codex command contract");
  expectEqual(ctx, env.get("CODEX_HOME")?.value, "/codex-home", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.CODEX_HOME", "cloud API workload CODEX_HOME contract");
  expectNoProxyIncludes(ctx, env.get("NO_PROXY")?.value, contract.noProxyRequired, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.NO_PROXY");
  expectNoProxyIncludes(ctx, env.get("no_proxy")?.value, contract.noProxyRequired, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.no_proxy");
  validateCodexApiForwarderArtifacts(ctx, podContainers, contract);
  validateCodexHomeMountArtifacts(ctx, container?.volumeMounts ?? [], volumes, contract);
  validateCodeAgentWorkspaceArtifacts(ctx, container?.volumeMounts ?? [], volumes, initContainers, workload?.spec?.strategy ?? null, workspacePvc, contract);
  expect(
    ctx,
    env.get("HWLAB_CODE_AGENT_OPENAI_BASE_URL")?.value !== contract.egress.forbiddenDirectBaseUrl,
    "forbidden_direct_egress",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.HWLAB_CODE_AGENT_OPENAI_BASE_URL",
    "cloud API workload Code Agent must not point directly at public api.openai.com",
    { expected: contract.egress.target, actual: env.get("HWLAB_CODE_AGENT_OPENAI_BASE_URL")?.value }
  );
  expectEqual(ctx, env.get(secretRef.env)?.valueFrom?.secretKeyRef?.name, secretRef.secretName, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.OPENAI_API_KEY.secretKeyRef.name", "cloud API workload Code Agent Secret name");
  expectEqual(ctx, env.get(secretRef.env)?.valueFrom?.secretKeyRef?.key, secretRef.secretKey, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.env.OPENAI_API_KEY.secretKeyRef.key", "cloud API workload Code Agent Secret key");
}

function expectNoProxyIncludes(ctx, value, required, path, label = "NO_PROXY contract") {
  const entries = new Set(String(value ?? "")
    .split(/[,;\s]+/u)
    .map((item) => item.trim().toLowerCase())
    .filter(Boolean));
  for (const item of required) {
    expect(ctx, entries.has(String(item).toLowerCase()), "missing_no_proxy_entry", path, `${label} includes ${item}`, { expected: item, actual: value });
  }
}

function validateCodexApiForwarderArtifacts(ctx, containers, contract) {
  const sidecar = (containers ?? []).find((entry) => entry.name === contract.forwarder.containerName);
  expect(ctx, Boolean(sidecar), "codex_api_forwarder_missing", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder", "cloud API pod includes codex-api loopback forwarder sidecar");
  if (!sidecar) return;
  expect(ctx, JSON.stringify(sidecar.command) === JSON.stringify(contract.forwarder.command), "codex_api_forwarder_command_mismatch", "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.command", "codex-api forwarder command");
  expect(
    ctx,
    (sidecar.ports ?? []).some((entry) => entry.name === contract.forwarder.portName && entry.containerPort === contract.forwarder.port),
    "codex_api_forwarder_port_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.ports",
    "codex-api forwarder exposes only a Pod-local container port"
  );
  const env = new Map((sidecar.env ?? []).map((entry) => [entry.name, entry.value]));
  expectEqual(ctx, env.get(contract.forwarder.listenHostEnv), "127.0.0.1", `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.env.${contract.forwarder.listenHostEnv}`, "codex-api forwarder loopback listen host env");
  expectEqual(ctx, env.get(contract.forwarder.upstreamEnv), contract.forwarder.upstreamBaseUrl, `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.env.${contract.forwarder.upstreamEnv}`, "codex-api forwarder upstream env");
  expectEqual(ctx, env.get(contract.forwarder.portEnv), String(contract.forwarder.port), `deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.env.${contract.forwarder.portEnv}`, "codex-api forwarder port env");
  expectNoProxyIncludes(ctx, env.get("NO_PROXY"), contract.noProxyRequired, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.env.NO_PROXY", "codex-api forwarder NO_PROXY contract");
  expectNoProxyIncludes(ctx, env.get("no_proxy"), contract.noProxyRequired, "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.containers.hwlab-codex-api-forwarder.env.no_proxy", "codex-api forwarder no_proxy contract");
}

function validateCodexHomeMountArtifacts(ctx, volumeMounts, volumes, contract) {
  expect(
    ctx,
    volumeMounts.some((entry) => entry.name === "hwlab-code-agent-codex-home" && entry.mountPath === contract.codexHome.path),
    "codex_home_mount_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumeMounts.hwlab-code-agent-codex-home",
    "cloud API workload CODEX_HOME writable mount"
  );
  expect(
    ctx,
    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
    ),
    "codex_config_mount_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumeMounts.hwlab-code-agent-codex-config",
    "cloud API workload Codex config.toml read-only mount"
  );
  expect(
    ctx,
    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
    ),
    "codex_auth_mount_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumeMounts.hwlab-code-agent-codex-auth",
    "cloud API workload Codex auth.json read-only mount"
  );
  expect(
    ctx,
    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)
    ),
    "codex_config_volume_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumes.hwlab-code-agent-codex-config",
    "cloud API workload Codex config ConfigMap ref"
  );
  expect(
    ctx,
    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)
    ),
    "codex_auth_volume_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumes.hwlab-code-agent-codex-auth",
    "cloud API workload Codex auth Secret ref"
  );
}

function validateCodeAgentWorkspaceArtifacts(ctx, volumeMounts, volumes, initContainers, strategy, pvc, contract) {
  const workspace = contract.workspace;
  expect(
    ctx,
    volumeMounts.some((entry) => entry.name === workspace.volumeName && entry.mountPath === workspace.mountPath && entry.readOnly !== true),
    "code_agent_workspace_mount_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumeMounts.hwlab-code-agent-workspace",
    "cloud API workload Code Agent workspace writable mount"
  );
  expect(
    ctx,
    volumes.some((entry) => entry.name === workspace.volumeName && entry.persistentVolumeClaim?.claimName === workspace.claimName),
    "code_agent_workspace_pvc_volume_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.volumes.hwlab-code-agent-workspace",
    "cloud API workload Code Agent workspace PVC volume"
  );
  expect(
    ctx,
    pvc?.kind === "PersistentVolumeClaim" && pvc?.metadata?.name === workspace.claimName,
    "code_agent_workspace_pvc_missing",
    "deploy/k8s/base/workloads.yaml.PersistentVolumeClaim.hwlab-code-agent-workspace",
    "Code Agent workspace PVC resource"
  );
  expect(
    ctx,
    (pvc?.spec?.accessModes ?? []).includes(workspace.accessMode),
    "code_agent_workspace_pvc_access_mode_mismatch",
    "deploy/k8s/base/workloads.yaml.PersistentVolumeClaim.hwlab-code-agent-workspace.spec.accessModes",
    "Code Agent workspace PVC uses ReadWriteOnce"
  );
  expectEqual(
    ctx,
    pvc?.spec?.resources?.requests?.storage,
    workspace.storage,
    "deploy/k8s/base/workloads.yaml.PersistentVolumeClaim.hwlab-code-agent-workspace.spec.resources.requests.storage",
    "Code Agent workspace PVC requested storage"
  );
  const initContainer = initContainers.find((entry) => entry.name === workspace.initContainerName);
  expect(
    ctx,
    Boolean(initContainer),
    "code_agent_workspace_init_container_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.initContainers.hwlab-code-agent-workspace-init",
    "cloud API workload initializes persistent Code Agent workspace"
  );
  expect(
    ctx,
    (initContainer?.volumeMounts ?? []).some((entry) => entry.name === workspace.volumeName && entry.mountPath === workspace.mountPath),
    "code_agent_workspace_init_mount_missing",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.initContainers.hwlab-code-agent-workspace-init.volumeMounts",
    "Code Agent workspace init container mounts the persistent workspace"
  );
  const initCommand = [...(initContainer?.command ?? []), ...(initContainer?.args ?? [])].join("\n");
  expect(
    ctx,
    initCommand.includes(workspace.sourcePath) && initCommand.includes(workspace.path) && initCommand.includes(workspace.initMarker),
    "code_agent_workspace_init_command_mismatch",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.initContainers.hwlab-code-agent-workspace-init.command",
    "Code Agent workspace init container uses copy-once /app bootstrap"
  );
  expectEqual(
    ctx,
    strategy?.type,
    workspace.rolloutStrategy,
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-api.strategy.type",
    "cloud API uses Recreate rollout for single-writer workspace PVC"
  );
}

function validateCodeAgentProxyTimeoutArtifacts(ctx, workloads) {
  const workloadItems = mapByServiceId(listItems(workloads));
  const cloudWebEnv = new Map((workloadItems.get("hwlab-cloud-web")?.spec?.template?.spec?.containers?.[0]?.env ?? []).map((entry) => [entry.name, entry.value]));
  const edgeProxyEnv = new Map((workloadItems.get("hwlab-edge-proxy")?.spec?.template?.spec?.containers?.[0]?.env ?? []).map((entry) => [entry.name, entry.value]));
  const cloudApiEnv = new Map((workloadItems.get("hwlab-cloud-api")?.spec?.template?.spec?.containers?.[0]?.env ?? []).map((entry) => [entry.name, entry.value]));
  expectEqual(ctx, cloudWebEnv.get("HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS"), codeAgentTransportTimeoutMs, "deploy/k8s/base/workloads.yaml.hwlab-cloud-web.env.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS", "Cloud Web workload same-origin Code Agent proxy timeout budget");
  expectEqual(ctx, edgeProxyEnv.get("HWLAB_EDGE_PROXY_TIMEOUT_MS"), codeAgentTransportTimeoutMs, "deploy/k8s/base/workloads.yaml.hwlab-edge-proxy.env.HWLAB_EDGE_PROXY_TIMEOUT_MS", "edge proxy workload Code Agent timeout budget");
  expect(
    ctx,
    Number.parseInt(cloudWebEnv.get("HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS") ?? "0", 10) > Number.parseInt(cloudApiEnv.get("HWLAB_CODE_AGENT_TIMEOUT_MS") ?? "0", 10),
    "code_agent_timeout_layering",
    "deploy/k8s/base/workloads.yaml.hwlab-cloud-web.env.HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS",
    "Cloud Web workload proxy timeout must exceed cloud-api Code Agent timeout",
    { expected: `>${cloudApiEnv.get("HWLAB_CODE_AGENT_TIMEOUT_MS")}`, actual: cloudWebEnv.get("HWLAB_CLOUD_WEB_PROXY_TIMEOUT_MS") }
  );
  expect(
    ctx,
    Number.parseInt(edgeProxyEnv.get("HWLAB_EDGE_PROXY_TIMEOUT_MS") ?? "0", 10) > Number.parseInt(cloudApiEnv.get("HWLAB_CODE_AGENT_TIMEOUT_MS") ?? "0", 10),
    "code_agent_timeout_layering",
    "deploy/k8s/base/workloads.yaml.hwlab-edge-proxy.env.HWLAB_EDGE_PROXY_TIMEOUT_MS",
    "Edge workload proxy timeout must exceed cloud-api Code Agent timeout",
    { expected: `>${cloudApiEnv.get("HWLAB_CODE_AGENT_TIMEOUT_MS")}`, actual: edgeProxyEnv.get("HWLAB_EDGE_PROXY_TIMEOUT_MS") }
  );
}

async function buildPlan() {
  const ctx = { checks: 0, diagnostics: [] };
  const [manifest, services, workloads, healthContract, masterEdge, frpc, frps] = await Promise.all([
    readJson("deploy/deploy.yaml"),
    readJson("deploy/k8s/base/services.yaml"),
    readJson("deploy/k8s/base/workloads.yaml"),
    readJson("deploy/k8s/dev/health-contract.yaml"),
    readJson("deploy/master-edge/health-contract.json"),
    parseToml("deploy/frp/frpc.dev.toml"),
    parseToml("deploy/frp/frps.dev.toml")
  ]);
  const source = validateSource(ctx, manifest);
  const rendered = renderPlan(source);
  validateFrpArtifacts(ctx, source, rendered, frpc, frps);
  validateK3sArtifacts(ctx, source, rendered, services, workloads, healthContract, masterEdge);
  const drift = ctx.diagnostics.filter((item) => item.code === "legacy_public_endpoint_drift");
  return {
    kind: "hwlab-deploy-contract-plan",
    mode: "dry-run",
    status: ctx.diagnostics.length === 0 ? "pass" : "blocked",
    source: "deploy/deploy.yaml",
    dryRunOnly: true,
    safety: {
      frpApply: false,
      kubectlApply: false,
      prod: false,
      restart: false
    },
    summary: {
      publicEndpoints: Object.keys(rendered.publicEndpoints).length,
      frpProxies: rendered.frpc.proxies.length,
      k3sServices: rendered.k3sServices.length,
      healthPath: rendered.health.path,
      legacyPublicEndpointDrift: drift.length,
      checks: ctx.checks
    },
    rendered,
    diagnostics: ctx.diagnostics,
    nextIntegration: ["hwlab edge apply", "deploy apply"]
  };
}

export async function runDeployContractPlanCli(argv = process.argv.slice(2)) {
  const args = parseArgs(argv);
  const plan = await buildPlan();
  process.stdout.write(`${JSON.stringify(plan, null, args.pretty ? 2 : 0)}\n`);
  if (args.check && plan.status !== "pass") {
    process.exitCode = 1;
  }
}

export function writeDeployContractPlanError(error) {
  process.stdout.write(`${JSON.stringify({
    kind: "hwlab-deploy-contract-plan",
    mode: "dry-run",
    status: "error",
    error: error instanceof Error ? error.message : String(error),
    safety: { frpApply: false, kubectlApply: false, prod: false, restart: false }
  })}\n`);
  process.exitCode = 1;
}
