import assert from "node:assert/strict";
import { test } from "bun:test";

import {
  projectPacDeliveryObserve,
  projectPacDeliveryObserveSnapshot,
  renderPacDeliveryObserve,
} from "./platform-infra-pac-delivery-observe";

const commit = "b".repeat(40);

function fixture(overrides: Record<string, unknown> = {}): Record<string, unknown> {
  return {
    target: { id: "NC01" },
    consumer: {
      id: "fixture",
      deliveryObservation: {
        runtimeEvidence: "required",
        configPath: "config/platform-infra/pipelines-as-code.yaml#consumers.fixture.deliveryObservation.runtimeEvidence",
        defaulted: false,
        fallbackReason: null,
      },
    },
    observation: { ok: true },
    summary: {
      latestPipelineRun: { name: "fixture-run", status: "True", reason: "Succeeded", sourceCommit: commit },
      pipelineRuns: [{ name: "fixture-run", status: "True", reason: "Succeeded", sourceCommit: commit }],
      artifact: { collector: { mode: "taskrun-status-only" } },
      argo: { sync: "Synced", health: "Healthy", revision: "a".repeat(40) },
      runtime: {
        workloads: [
          { namespace: "fixture", deployment: "api", sourceCommit: commit, readyReplicas: 1, replicas: 1, digest: "sha256:abc" },
          { namespace: "fixture", deployment: "old", sourceCommit: "c".repeat(40), readyReplicas: 1, replicas: 1 },
        ],
      },
      ...overrides,
    },
  };
}

test("delivery observe completes from one exact source capture", () => {
  const result = projectPacDeliveryObserve({ status: fixture(), sourceCommit: commit });
  assert.equal(result.status, "complete");
  assert.equal(result.remoteCaptureCount, 1);
  assert.equal((result.pipeline as Record<string, unknown>).sourceMatched, true);
  assert.equal((result.runtime as Record<string, unknown>).matchingWorkloadCount, 1);
  assert.equal(result.firstBreak, null);
  assert.match(renderPacDeliveryObserve(result).join("\n"), /REMOTE_CAPTURE_COUNT  1/u);
});

test("delivery observe preserves exact runtime evidence while surfacing Argo degradation", () => {
  const result = projectPacDeliveryObserve({
    status: fixture({
      argo: {
        sync: "OutOfSync",
        health: "Degraded",
        firstDegradedResource: { kind: "Deployment", namespace: "fixture", name: "worker" },
        firstCondition: { type: "ComparisonError", message: "bounded" },
      },
    }),
    sourceCommit: commit,
  });
  assert.equal(result.status, "partial");
  assert.equal(result.ok, true);
  assert.equal((result.firstBreak as Record<string, unknown>).code, "argo-not-ready");
});

test("delivery observe blocks a mismatched source commit without accepting another workload", () => {
  const result = projectPacDeliveryObserve({ status: fixture(), sourceCommit: "d".repeat(40) });
  assert.equal(result.status, "blocked");
  assert.equal(result.ok, false);
  assert.equal((result.firstBreak as Record<string, unknown>).code, "pipeline-source-commit-mismatch");
});

test("delivery observe selects an exact source from the bounded status capture", () => {
  const older = "d".repeat(40);
  const status = fixture();
  const summary = status.summary as Record<string, unknown>;
  summary.latestPipelineRun = { name: "newer-run", status: "True", sourceCommit: commit };
  summary.pipelineRuns = [
    summary.latestPipelineRun,
    { name: "older-run", status: "True", reason: "Succeeded", sourceCommit: older },
  ];
  summary.runtime = {
    workloads: [{ namespace: "fixture", deployment: "api", sourceCommit: older, readyReplicas: 1, replicas: 1 }],
  };
  const result = projectPacDeliveryObserve({ status, sourceCommit: older });
  assert.equal(result.status, "complete");
  assert.equal((result.pipeline as Record<string, unknown>).id, "older-run");
  assert.equal((result.pipeline as Record<string, unknown>).selectedFrom, "bounded-status-history");
});

test("delivery observe treats an intentionally scaled-to-zero workload as ready", () => {
  const status = fixture();
  (status.summary as Record<string, unknown>).runtime = {
    workloads: [{ namespace: "fixture", deployment: "idle", sourceCommit: commit, readyReplicas: 0, replicas: 0 }],
  };
  const result = projectPacDeliveryObserve({ status, sourceCommit: commit });
  assert.equal(result.status, "complete");
  assert.equal((result.runtime as Record<string, unknown>).ready, true);
});

test("delivery observe projects a lightweight node snapshot without a second status source", () => {
  const result = projectPacDeliveryObserveSnapshot({
    sourceCommit: commit,
    target: { id: "NC01" },
    consumer: { id: "fixture" },
    snapshot: {
      ok: true,
      observation: { ok: true, status: "succeeded" },
      consumers: [{
        consumer: "fixture",
        latestPipelineRunSummary: { name: "fixture-run", status: "True", reason: "Succeeded", sourceCommit: commit },
        pipelineRuns: [{ name: "fixture-run", status: "True", reason: "Succeeded", sourceCommit: commit }],
        argo: { sync: "Synced", health: "Healthy" },
        runtime: {
          workloads: [{ namespace: "fixture", deployment: "api", sourceCommit: commit, readyReplicas: 1, replicas: 1 }],
        },
      }],
    },
  });
  assert.equal(result.status, "complete");
  assert.deepEqual(result.artifactEvidence, { mode: "deferred-single-snapshot", deferred: true });
  assert.equal(result.remoteCaptureCount, 1);
});

test("delivery observe preserves a typed snapshot read failure", () => {
  const result = projectPacDeliveryObserveSnapshot({
    sourceCommit: commit,
    target: { id: "NC01" },
    consumer: { id: "fixture" },
    snapshot: {
      ok: false,
      observation: { ok: true, status: "succeeded" },
      readErrors: [{
        stage: "pipeline-runs",
        code: "pac-node-pipeline-runs-read-failed",
        exitCode: 124,
      }],
      consumers: [{ consumer: "fixture" }],
    },
  });
  assert.equal(result.status, "blocked");
  assert.deepEqual(result.firstBreak, {
    code: "pac-node-pipeline-runs-read-failed",
    phase: "pipeline-runs",
    exitCode: 124,
  });
  assert.equal((result.readErrors as unknown[]).length, 1);
});

test("delivery observe completes a configuration-only consumer without runtime workloads", () => {
  const status = fixture({ runtime: { workloads: [] } });
  status.consumer = {
    id: "fixture",
    deliveryObservation: {
      runtimeEvidence: "not-applicable",
      configPath: "config/platform-infra/pipelines-as-code.yaml#consumers.fixture.deliveryObservation.runtimeEvidence",
      defaulted: false,
      fallbackReason: null,
    },
  };
  const result = projectPacDeliveryObserve({ status, sourceCommit: commit });
  assert.equal(result.status, "complete");
  assert.equal((result.runtime as Record<string, unknown>).applicable, false);
  assert.equal((result.runtime as Record<string, unknown>).ready, null);
  assert.deepEqual(result.firstBreak, null);
  assert.deepEqual((result.warnings as Record<string, unknown>[])[0], {
    code: "runtime-evidence-not-applicable",
    phase: "runtime",
    blocking: false,
    mode: "not-applicable",
    configPath: "config/platform-infra/pipelines-as-code.yaml#consumers.fixture.deliveryObservation.runtimeEvidence",
  });
});

test("delivery observe defaults missing non-core runtime evidence mode without blocking", () => {
  const status = fixture();
  status.consumer = { id: "fixture" };
  const result = projectPacDeliveryObserve({ status, sourceCommit: commit });
  assert.equal(result.status, "complete");
  assert.equal((result.runtime as Record<string, unknown>).evidenceMode, "required");
  assert.equal((result.warnings as Record<string, unknown>[])[0]?.code, "runtime-evidence-mode-defaulted");
  assert.equal((result.warnings as Record<string, unknown>[])[0]?.blocking, false);
});
