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 } from 'vitest';
import {
	getSuggestedNextCommands,
	indexWorkspace,
	listDoctorScopeSuggestions,
} from "../workspace-index.ts";

test("workspace index: indexes active milestone/slice/task and suggests commands", async () => {
	const base = mkdtempSync(join(tmpdir(), "sf-workspace-index-test-"));
	const sf = join(base, ".sf");
	const mDir = join(sf, "milestones", "M001");
	const sDir = join(mDir, "slices", "S01");
	mkdirSync(join(sDir, "tasks"), { recursive: true });

	writeFileSync(
		join(mDir, "M001-ROADMAP.md"),
		`# M001: Demo Milestone\n\n## Slices\n- [ ] **S01: Demo Slice** \`risk:low\` \`depends:[]\`\n  > After this: demo works\n`,
	);
	writeFileSync(
		join(sDir, "S01-PLAN.md"),
		`# S01: Demo Slice\n\n**Goal:** Demo\n**Demo:** Demo\n\n## Must-Haves\n- done\n\n## Adversarial Review\n\n### Partner Review\nThe plan is scoped and executable.\n\n### Combatant Review\nThe main risk is covered by the task boundary.\n\n### Architect Review\nThe implementation path is acceptable for the fixture.\n\n## Tasks\n- [ ] **T01: Implement thing** \`est:10m\`\n  Task is in progress.\n`,
	);
	writeFileSync(
		join(sDir, "tasks", "T01-PLAN.md"),
		`# T01: Implement thing\n\n## Steps\n- do it\n`,
	);

	try {
		const index = await indexWorkspace(base);
		assert.equal(index.active.milestoneId, "M001");
		assert.equal(index.active.sliceId, "S01");
		assert.equal(index.active.taskId, "T01");
		assert.ok(index.scopes.some((s) => s.scope === "M001/S01"));
		assert.ok(index.scopes.some((s) => s.scope === "M001/S01/T01"));

		const suggestions = await listDoctorScopeSuggestions(base);
		assert.equal(suggestions[0].value, "M001/S01");
		assert.ok(suggestions.some((item) => item.value === "M001/S01/T01"));

		const commands = await getSuggestedNextCommands(base);
		assert.ok(commands.includes("/sf autonomous"));
		assert.ok(commands.includes("/sf doctor M001/S01"));
		assert.ok(commands.includes("/sf status"));
	} finally {
		rmSync(base, { recursive: true, force: true });
	}
});
