import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test, afterEach } from 'vitest';
import { buildCompleteSlicePrompt } from "../auto-prompts.ts";
import {
	closeDatabase,
	insertMilestone,
	insertSlice,
	insertTask,
	openDatabase,
} from "../sf-db.ts";

test("complete-slice prompt treats skipped tasks as non-executable gaps", async (t) => {
	const tmp = mkdtempSync(join(tmpdir(), "sf-complete-skip-"));
	afterEach(() => {
		closeDatabase();
		rmSync(tmp, { recursive: true, force: true });
	});

	mkdirSync(join(tmp, ".sf"), { recursive: true });
	openDatabase(join(tmp, ".sf", "sf.db"));

	const sliceDir = join(tmp, ".sf", "milestones", "M001", "slices", "S05");
	mkdirSync(join(sliceDir, "tasks"), { recursive: true });
	writeFileSync(
		join(tmp, ".sf", "milestones", "M001", "M001-ROADMAP.md"),
		"# M001\n",
	);
	writeFileSync(
		join(sliceDir, "S05-PLAN.md"),
		[
			"# S05",
			"",
			"## Verification",
			"Run docker compose up -d and poll staging health.",
			"",
		].join("\n"),
	);
	writeFileSync(
		join(sliceDir, "tasks", "T01-SUMMARY.md"),
		["---", "id: T01", "---", "", "# T01", "Existing tests passed.", ""].join(
			"\n",
		),
	);

	insertMilestone({ id: "M001", title: "Test Milestone" });
	insertSlice({
		id: "S05",
		milestoneId: "M001",
		title: "Final Verification",
		status: "active",
	});
	insertTask({
		id: "T01",
		sliceId: "S05",
		milestoneId: "M001",
		title: "Run focused tests",
		status: "complete",
	});
	insertTask({
		id: "T02",
		sliceId: "S05",
		milestoneId: "M001",
		title: "Validate docker-compose staging stack starts cleanly",
		status: "skipped",
	});

	const prompt = await buildCompleteSlicePrompt(
		"M001",
		"Test Milestone",
		"S05",
		"Final Verification",
		tmp,
	);

	assert.match(prompt, /### Skipped Tasks/);
	assert.match(
		prompt,
		/T02: Validate docker-compose staging stack starts cleanly/,
	);
	assert.match(
		prompt,
		/do not execute verification that belongs only to those skipped tasks/,
	);
});
