import assert from "node:assert/strict";
import {
	existsSync,
	mkdirSync,
	mkdtempSync,
	readFileSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";

import { promoteActionableRecords } from "../record-promoter.js";

const tmpRoots = [];

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

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

test("promoteActionableRecords_creates_bare_slice_id_directories", () => {
	const projectRoot = makeProject();
	const recordPath = join(
		projectRoot,
		"docs",
		"records",
		"2026-05-05-path-shape.md",
	);
	writeFileSync(
		recordPath,
		[
			"---",
			"actionable: true",
			"promoted: false",
			"---",
			"",
			"## Gap One Needs Long Title",
			"",
			"Finding one.",
			"",
			"## Gap Two Also Needs Long Title",
			"",
			"Finding two.",
			"",
		].join("\n"),
	);

	const result = promoteActionableRecords(projectRoot);

	assert.equal(result.promoted.length, 1);
	assert.ok(
		existsSync(join(projectRoot, ".sf", "milestones", "M001", "slices", "S01")),
	);
	assert.ok(
		existsSync(join(projectRoot, ".sf", "milestones", "M001", "slices", "S02")),
	);
	assert.equal(
		existsSync(
			join(
				projectRoot,
				".sf",
				"milestones",
				"M001",
				"slices",
				"S01-gap-one-needs-long-title",
			),
		),
		false,
	);
	assert.equal(
		existsSync(
			join(
				projectRoot,
				".sf",
				"milestones",
				"M001",
				"slices",
				"S02-gap-two-also-needs-long-title",
			),
		),
		false,
	);
	assert.match(readFileSync(recordPath, "utf-8"), /promoted_to: M001/);
});
