import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";
import { closeoutUnit } from "../uok/auto-unit-closeout.js";
import {
	_resetLogs,
	drainLogs,
	setStderrLoggingEnabled,
} from "../workflow-logger.js";

const tmpRoots = [];

afterEach(() => {
	for (const dir of tmpRoots.splice(0)) {
		rmSync(dir, { recursive: true, force: true });
	}
	_resetLogs();
});

function makeProject() {
	const root = mkdtempSync(join(tmpdir(), "sf-closeout-"));
	tmpRoots.push(root);
	mkdirSync(join(root, ".sf"), { recursive: true });
	return root;
}

test("closeoutUnit_when_activity_log_exists_imports_memory_extractor_without_warning", async () => {
	const root = makeProject();
	const previousStderr = setStderrLoggingEnabled(false);
	_resetLogs();
	try {
		const ctx = {
			model: { provider: "test", id: "test-model" },
			modelRegistry: {
				getAvailable: () => [],
			},
			sessionManager: {
				getEntries: () => [
					{
						role: "assistant",
						content: "verification complete",
					},
				],
			},
		};

		const activityFile = await closeoutUnit(
			ctx,
			root,
			"execute-task",
			"M001/S01/T01",
			Date.now(),
			{},
		);

		assert.match(activityFile, /execute-task-M001-S01-T01\.jsonl$/);
		const warnings = drainLogs();
		assert.equal(
			warnings.some((entry) => entry.message.includes("memory-extractor.js")),
			false,
		);
	} finally {
		setStderrLoggingEnabled(previousStderr);
	}
});
