/**
 * doctor-runtime-stale-units.test.mjs - stale autonomous unit cleanup.
 *
 * Purpose: prove doctor clears active runtime unit claims when no live auto.lock
 * owner exists, so autonomous dispatch is not blocked by dead headless sessions.
 */
import assert from "node:assert/strict";
import {
	existsSync,
	mkdirSync,
	mkdtempSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, test } from "vitest";
import { runSFDoctor } from "../doctor.js";

const tmpDirs = [];

afterEach(() => {
	while (tmpDirs.length > 0) {
		const dir = tmpDirs.pop();
		if (dir) rmSync(dir, { recursive: true, force: true });
	}
});

function makeProject() {
	const dir = mkdtempSync(join(tmpdir(), "sf-doctor-stale-units-"));
	tmpDirs.push(dir);
	mkdirSync(join(dir, ".sf", "runtime", "units"), { recursive: true });
	return dir;
}

describe("doctor stale unit runtime cleanup", () => {
	test("runSFDoctor_fix_removes_active_unit_records_without_live_lock_owner", async () => {
		const project = makeProject();
		const runtimePath = join(
			project,
			".sf",
			"runtime",
			"units",
			"plan-slice-M010-S07.json",
		);
		writeFileSync(
			runtimePath,
			JSON.stringify(
				{
					version: 1,
					unitType: "plan-slice",
					unitId: "M010/S07",
					phase: "dispatched",
					status: "running",
					startedAt: Date.now() - 60_000,
					updatedAt: Date.now() - 60_000,
				},
				null,
				2,
			),
		);

		const report = await runSFDoctor(project, {
			fix: true,
			fixLevel: "all",
			scope: "project",
		});

		assert.equal(
			report.issues.some((issue) => issue.code === "stale_active_unit_runtime"),
			true,
		);
		assert.equal(existsSync(runtimePath), false);
		assert.ok(
			report.fixesApplied.includes(
				"cleared 1 stale active unit runtime record(s)",
			),
		);
	});
});
