import assert from "node:assert/strict";
import { mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "vitest";
import { resolveAutoSupervisorConfig } from "../preferences.js";
import {
	readUnitRuntimeRecord,
	writeUnitRuntimeRecord,
} from "../uok/unit-runtime.js";

test("resolveAutoSupervisorConfig provides safe timeout defaults", () => {
	const supervisor = resolveAutoSupervisorConfig();
	assert.equal(supervisor.soft_timeout_minutes, 20);
	assert.equal(supervisor.idle_timeout_minutes, 10);
	assert.equal(supervisor.hard_timeout_minutes, 30);
	assert.equal(supervisor.solver_max_iterations, 25);
});

test("writeUnitRuntimeRecord persists progress and recovery metadata defaults", () => {
	const base = mkdtempSync(join(tmpdir(), "sf-auto-supervisor-"));
	const startedAt = 1234567890;

	writeUnitRuntimeRecord(base, "plan-milestone", "M010", startedAt, {
		phase: "dispatched",
		lastProgressAt: startedAt,
		progressCount: 1,
		lastProgressKind: "dispatch",
	});

	const runtime = readUnitRuntimeRecord(base, "plan-milestone", "M010");
	assert.ok(runtime);
	assert.equal(runtime.phase, "dispatched");
	assert.equal(runtime.lastProgressAt, startedAt);
	assert.equal(runtime.progressCount, 1);
	assert.equal(runtime.lastProgressKind, "dispatch");
	assert.equal(runtime.recoveryAttempts, 0);
});

test("writeUnitRuntimeRecord keeps explicit recovery attempt fields", () => {
	const base = mkdtempSync(join(tmpdir(), "sf-auto-supervisor-"));
	const startedAt = 2234567890;

	writeUnitRuntimeRecord(base, "research-milestone", "M011", startedAt, {
		phase: "timeout",
		recoveryAttempts: 2,
		lastRecoveryReason: "idle",
		lastProgressAt: startedAt + 50,
		progressCount: 3,
		lastProgressKind: "recovery-retry",
	});

	const runtime = JSON.parse(
		readFileSync(
			join(base, ".sf/runtime/units/research-milestone-M011.json"),
			"utf8",
		),
	);
	assert.equal(runtime.recoveryAttempts, 2);
	assert.equal(runtime.lastRecoveryReason, "idle");
	assert.equal(runtime.lastProgressKind, "recovery-retry");
});
