import assert from "node:assert/strict";
import test from "node:test";

import { createServer } from "node:http";
import { once } from "node:events";
import { pathToFileURL } from "node:url";

import { buildMetricsText, isMainModule, probeExtraMetrics, probeTarget, requestTarget, sanitizeExtraMetricsText, sanitizeLabelValue } from "./metrics-sidecar.mjs";

test("metrics text exposes stable HWLAB labels without sensitive identifiers", () => {
  const text = buildMetricsText({
    env: {
      HWLAB_METRICS_SERVICE_ID: "hwlab-cloud-api",
      HWLAB_METRICS_NAMESPACE: "hwlab-v02",
      HWLAB_METRICS_GITOPS_TARGET: "v02"
    },
    probe: { configured: true, success: true, statusCode: 200, durationSeconds: 0.012 }
  });

  assert.match(text, /hwlab_service_up\{service="hwlab-cloud-api",namespace="hwlab-v02",gitops_target="v02"\} 1/u);
  assert.match(text, /hwlab_service_health_probe_success\{service="hwlab-cloud-api",namespace="hwlab-v02",gitops_target="v02"\} 1/u);
  assert.doesNotMatch(text, /traceId|sessionId|conversationId|threadId|runId|commandId|jobId/iu);
  assert.doesNotMatch(text, /prompt|assistant text|device output|secret|api key/iu);
});

test("label sanitization keeps metrics labels low-risk", () => {
  assert.equal(sanitizeLabelValue("hwlab/cloud api\ntraceId=trc_1"), "hwlab_cloud_api_traceId_trc_1");
  assert.equal(sanitizeLabelValue(""), "unknown");
});

test("health target probe uses Node HTTP request against cluster-local style targets", async () => {
  const server = createServer((request, response) => {
    if (request.url === "/health/live") {
      response.writeHead(200, { "content-type": "application/json" });
      response.end(JSON.stringify({ status: "ok" }));
      return;
    }
    response.writeHead(404);
    response.end();
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  try {
    const address = server.address();
    const probe = await requestTarget({ targetUrl: `http://127.0.0.1:${address.port}/health/live`, timeoutMs: 1000 });
    assert.equal(probe.configured, true);
    assert.equal(probe.success, true);
    assert.equal(probe.statusCode, 200);
    assert.ok(probe.durationSeconds >= 0);
  } finally {
    server.close();
    await once(server, "close");
  }
});

test("health target probe degrades invalid URLs to failed metrics", async () => {
  const probe = await probeTarget({ targetUrl: "not a url", timeoutMs: 1000 });
  assert.deepEqual({ configured: probe.configured, success: probe.success, statusCode: probe.statusCode }, {
    configured: true,
    success: false,
    statusCode: 0
  });
});

test("extra metrics text is appended only for HWLAB prometheus metrics", () => {
  const text = buildMetricsText({
    env: {
      HWLAB_METRICS_SERVICE_ID: "hwlab-cloud-api",
      HWLAB_METRICS_NAMESPACE: "hwlab-v02",
      HWLAB_METRICS_GITOPS_TARGET: "v02"
    },
    probe: { configured: true, success: true, statusCode: 200, durationSeconds: 0.012 },
    extraMetrics: {
      configured: true,
      success: true,
      statusCode: 200,
      durationSeconds: 0.034,
      text: sanitizeExtraMetricsText([
        "# HELP hwlab_webui_performance_sample_total samples",
        "# TYPE hwlab_webui_performance_sample_total counter",
        "hwlab_webui_performance_sample_total{service=\"hwlab-cloud-web\",namespace=\"hwlab-v02\"} 1",
        "nodejs_process_secret{token=\"abc\"} 1"
      ].join("\n"))
    }
  });

  assert.match(text, /hwlab_service_extra_metrics_success\{service="hwlab-cloud-api",namespace="hwlab-v02",gitops_target="v02"\} 1/u);
  assert.match(text, /hwlab_webui_performance_sample_total\{service="hwlab-cloud-web",namespace="hwlab-v02"\} 1/u);
  assert.doesNotMatch(text, /nodejs_process_secret|token="abc"/u);
});

test("extra metrics probe fetches cluster-local prometheus text", async () => {
  const server = createServer((request, response) => {
    if (request.url === "/v1/web-performance/metrics") {
      response.writeHead(200, { "content-type": "text/plain" });
      response.end("hwlab_webui_performance_sample_total{service=\"hwlab-cloud-web\"} 2\n");
      return;
    }
    response.writeHead(404);
    response.end();
  });
  server.listen(0, "127.0.0.1");
  await once(server, "listening");
  try {
    const address = server.address();
    const probe = await probeExtraMetrics({ targetUrl: `http://127.0.0.1:${address.port}/v1/web-performance/metrics`, timeoutMs: 1000 });
    assert.equal(probe.configured, true);
    assert.equal(probe.success, true);
    assert.match(probe.text, /hwlab_webui_performance_sample_total/u);
  } finally {
    server.close();
    await once(server, "close");
  }
});

test("entrypoint detection follows ConfigMap symlink paths", () => {
  const realScriptPath = "/var/run/configmaps/hwlab-v02-metrics-sidecar/..2026_06_05/metrics-sidecar.mjs";
  const mountedScriptPath = "/metrics/metrics-sidecar.mjs";

  assert.equal(isMainModule({ moduleUrl: pathToFileURL(mountedScriptPath).href, argvPath: mountedScriptPath }), true);
  assert.equal(isMainModule({
    moduleUrl: pathToFileURL(realScriptPath).href,
    argvPath: mountedScriptPath,
    realpath: () => realScriptPath
  }), true);
  assert.equal(isMainModule({
    moduleUrl: pathToFileURL(realScriptPath).href,
    argvPath: mountedScriptPath,
    realpath: () => "/other/metrics-sidecar.mjs"
  }), false);
});
