import assert from "node:assert/strict";
import { test } from "vitest";
import {
	normalizeUnitLineage,
	recordUnitLineageEvent,
} from "../uok/unit-lineage.js";

test("normalizeUnitLineage_when_worker_ids_repeat_returns_deduplicated_lineage", () => {
	assert.deepEqual(
		normalizeUnitLineage({
			unitType: "execute-task",
			unitId: "M001/S01/T01",
			workerSessionIds: ["worker-1", "worker-1"],
			currentWorkerSessionId: "worker-2",
			completedWorkerSessionId: "worker-3",
			failedWorkerSessionIds: ["worker-4", "worker-4"],
			status: "started",
		}),
		{
			unitType: "execute-task",
			unitId: "M001/S01/T01",
			status: "started",
			workerSessionIds: ["worker-1", "worker-2", "worker-3", "worker-4"],
			currentWorkerSessionId: "worker-2",
			completedWorkerSessionId: "worker-3",
			failedWorkerSessionIds: ["worker-4"],
			events: [],
		},
	);
});

test("recordUnitLineageEvent_when_worker_starts_marks_current_session", () => {
	const lineage = recordUnitLineageEvent(
		{ unitType: "execute-task", unitId: "M001/S01/T01" },
		{
			ts: "2026-05-08T17:00:00.000Z",
			status: "started",
			workerSessionId: "worker-1",
			spawnId: "spawn-1",
		},
	);

	assert.equal(lineage.status, "started");
	assert.deepEqual(lineage.workerSessionIds, ["worker-1"]);
	assert.equal(lineage.currentWorkerSessionId, "worker-1");
	assert.equal(lineage.events[0].spawnId, "spawn-1");
});

test("recordUnitLineageEvent_when_worker_completes_moves_current_to_completed", () => {
	const started = recordUnitLineageEvent(
		{},
		{
			status: "started",
			workerSessionId: "worker-1",
		},
	);
	const completed = recordUnitLineageEvent(started, {
		status: "completed",
		workerSessionId: "worker-1",
	});

	assert.equal(completed.status, "completed");
	assert.equal(completed.currentWorkerSessionId, null);
	assert.equal(completed.completedWorkerSessionId, "worker-1");
	assert.deepEqual(completed.failedWorkerSessionIds, []);
});

test("recordUnitLineageEvent_when_worker_fails_tracks_failed_session", () => {
	const lineage = recordUnitLineageEvent(
		{
			workerSessionIds: ["worker-1"],
			currentWorkerSessionId: "worker-1",
		},
		{
			status: "failed",
			workerSessionId: "worker-1",
			note: "provider timeout",
		},
	);

	assert.equal(lineage.status, "failed");
	assert.equal(lineage.currentWorkerSessionId, null);
	assert.deepEqual(lineage.failedWorkerSessionIds, ["worker-1"]);
	assert.equal(lineage.events[0].note, "provider timeout");
});

test("recordUnitLineageEvent_when_unit_blocks_clears_current_worker", () => {
	const lineage = recordUnitLineageEvent(
		{
			unitType: "execute-task",
			unitId: "M001/S01/T01",
			workerSessionIds: ["worker-1"],
			currentWorkerSessionId: "worker-1",
		},
		{
			status: "blocked",
			workerSessionId: "worker-1",
			note: "artifact verification failed",
		},
	);

	assert.equal(lineage.status, "blocked");
	assert.equal(lineage.currentWorkerSessionId, null);
	assert.deepEqual(lineage.workerSessionIds, ["worker-1"]);
});
