import assert from "node:assert/strict";

import {
  applyRuntimeLaneDeployConfig,
  isNamedRuntimeLane,
  isRuntimeLane,
  isVersionRuntimeLane,
  runtimeNamespaceForRuntimeLane,
  runtimeRelativePathForRuntimeLane
} from "./runtime-lane.ts";
import {
  gitopsPathForProfile,
  namespaceNameForProfile,
  parseArgs,
  runtimeFrpConfigForProfile,
  runtimePathForProfile,
  transformServices
} from "./gitops-render/core.mjs";
import { nodeFrpcManifest } from "./gitops-render/runtime-manifests.mjs";

const namedLaneDeploy = {
  nodes: {
    NC01: {
      gitopsRoot: "deploy/gitops/node/nc01",
      sourceRepo: "git@github.com:pikasTech/HWLAB.git"
    }
  },
  lanes: {
    production: {
      name: "Production",
      node: "NC01",
      sourceBranch: "release",
      gitopsBranch: "hwlab-production",
      gitReadUrl: "http://gitea.example/mirrors/hwlab.git",
      gitWriteUrl: "http://git-mirror-write.example/pikasTech/HWLAB.git",
      artifactCatalog: "deploy/artifact-catalog.production.json",
      runtimePath: "runtime-production",
      namespace: "hwlab-production",
      imageTagMode: "full",
      publicEndpoints: {
        frontend: "https://hwlab.example",
        api: "https://api.hwlab.example"
      },
      publicServices: {
        nodes: {
          NC01: [{
            name: "hwlab-cloud-web-public",
            selector: { "app.kubernetes.io/name": "hwlab-cloud-web" },
            port: 80,
            targetPort: 8080,
            nodePort: 32010
          }]
        }
      },
      frp: {
        server: { address: "203.0.113.10", bindPort: 22000 },
        proxies: [
          { name: "production-web", endpointId: "frontend", localHost: "web.hwlab-production.svc.cluster.local", localPort: 8080, remotePort: 22090 },
          { name: "production-api", endpointId: "api", localHost: "api.hwlab-production.svc.cluster.local", localPort: 6667, remotePort: 22088 }
        ]
      },
      envReuseServices: ["hwlab-cloud-web"],
      serviceDeclarations: {
        "hwlab-cloud-web": { healthPort: 8080, healthPath: "/health/live" }
      }
    }
  }
};

const defaultArgs = {
  lane: "production",
  nodeId: "node",
  outDir: "deploy/gitops/node",
  gitopsRoot: "deploy/gitops/node",
  sourceBranch: "node",
  gitopsBranch: "node-gitops",
  catalogPath: "deploy/artifact-catalog.dev.json",
  imageTagMode: "full",
  runtimeEndpoint: "http://74.48.78.17:17667",
  webEndpoint: "http://74.48.78.17:17666",
  sourceRepo: "git@github.com:pikasTech/HWLAB.git"
};

assert.equal(isRuntimeLane("production"), true);
assert.equal(isNamedRuntimeLane("production"), true);
assert.equal(isVersionRuntimeLane("production"), false);
assert.equal(isVersionRuntimeLane("v03"), true);
assert.equal(parseArgs(["--lane", "production", "--no-write"]).lane, "production");

const resolved = applyRuntimeLaneDeployConfig(defaultArgs, namedLaneDeploy);
assert.deepEqual({
  nodeId: resolved.nodeId,
  gitopsRoot: resolved.gitopsRoot,
  sourceBranch: resolved.sourceBranch,
  gitopsBranch: resolved.gitopsBranch,
  gitReadUrl: resolved.gitReadUrl,
  gitWriteUrl: resolved.gitWriteUrl,
  catalogPath: resolved.catalogPath,
  runtimeEndpoint: resolved.runtimeEndpoint,
  webEndpoint: resolved.webEndpoint
}, {
  nodeId: "NC01",
  gitopsRoot: "deploy/gitops/node/nc01",
  sourceBranch: "release",
  gitopsBranch: "hwlab-production",
  gitReadUrl: "http://gitea.example/mirrors/hwlab.git",
  gitWriteUrl: "http://git-mirror-write.example/pikasTech/HWLAB.git",
  catalogPath: "deploy/artifact-catalog.production.json",
  runtimeEndpoint: "https://api.hwlab.example",
  webEndpoint: "https://hwlab.example"
});
assert.equal(runtimeNamespaceForRuntimeLane(namedLaneDeploy, "production"), "hwlab-production");
assert.equal(runtimeRelativePathForRuntimeLane(namedLaneDeploy, "production"), "runtime-production");
assert.equal(namespaceNameForProfile("production", namedLaneDeploy), "hwlab-production");
assert.equal(runtimePathForProfile("production", namedLaneDeploy), "runtime-production");
assert.equal(
  gitopsPathForProfile(resolved, "production", namedLaneDeploy),
  "deploy/gitops/node/nc01/runtime-production"
);

const services = transformServices({
  services: { apiVersion: "v1", kind: "List", items: [] },
  namespace: "hwlab-production",
  labels: {},
  annotations: {},
  profile: "production",
  deploy: namedLaneDeploy,
  nodeId: "NC01"
});
assert.deepEqual(services.items[0].spec.ports[0], { name: "http", port: 80, targetPort: 8080, nodePort: 32010 });

const frp = runtimeFrpConfigForProfile(namedLaneDeploy, "production", { nodeId: "NC01" });
assert.deepEqual({
  serverAddr: frp.serverAddr,
  serverPort: frp.serverPort,
  webLocalHost: frp.webLocalHost,
  webLocalPort: frp.webLocalPort,
  webRemotePort: frp.webRemotePort,
  edgeLocalHost: frp.edgeLocalHost,
  edgeLocalPort: frp.edgeLocalPort,
  edgeRemotePort: frp.edgeRemotePort
}, {
  serverAddr: "203.0.113.10",
  serverPort: 22000,
  webLocalHost: "web.hwlab-production.svc.cluster.local",
  webLocalPort: 8080,
  webRemotePort: 22090,
  edgeLocalHost: "api.hwlab-production.svc.cluster.local",
  edgeLocalPort: 6667,
  edgeRemotePort: 22088
});

const frpDisabledDeploy = structuredClone(namedLaneDeploy);
frpDisabledDeploy.lanes.production.frp = { enabled: false };
assert.deepEqual(nodeFrpcManifest({ profile: "production", deploy: frpDisabledDeploy }).items, []);

const incompleteDeploy = structuredClone(namedLaneDeploy);
delete incompleteDeploy.lanes.production.namespace;
assert.throws(
  () => applyRuntimeLaneDeployConfig(defaultArgs, incompleteDeploy),
  /deploy\.lanes\.production\.namespace must be a non-empty string/u
);

const versionLaneDeploy = {
  nodes: { G14: { gitopsRoot: "deploy/gitops/node/G14", publicHost: "74.48.78.17" } },
  lanes: { v03: { node: "G14" } }
};
const versionResolved = applyRuntimeLaneDeployConfig({ ...defaultArgs, lane: "v03" }, versionLaneDeploy);
assert.equal(versionResolved.sourceBranch, "v0.3");
assert.equal(versionResolved.gitopsBranch, "v0.3-gitops");
assert.equal(versionResolved.catalogPath, "deploy/artifact-catalog.v03.json");
assert.equal(runtimeNamespaceForRuntimeLane(versionLaneDeploy, "v03"), "hwlab-v03");
assert.equal(runtimeRelativePathForRuntimeLane(versionLaneDeploy, "v03"), "runtime-v03");

console.log(JSON.stringify({ ok: true, tests: 20, namedLane: "production", versionLane: "v03" }));
