import assert from "node:assert/strict";
import {
	existsSync,
	mkdirSync,
	mkdtempSync,
	rmSync,
	writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, test } from "vitest";
import {
	ensureAgenticDocsScaffold,
	SCAFFOLD_FILES,
} from "../agentic-docs-scaffold.js";
import { checkScaffoldFreshness } from "../doctor-runtime-checks.js";
import { stampScaffoldFile } from "../scaffold-versioning.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-agentic-docs-scaffold-"));
	tmpRoots.push(root);
	return root;
}

function writeLegacyPendingScaffold(root, relPath) {
	const target = join(root, relPath);
	mkdirSync(dirname(target), { recursive: true });
	writeFileSync(target, `# ${relPath}\n`, "utf-8");
	stampScaffoldFile(target, relPath, "2.75.0", "pending");
}

test("ensureAgenticDocsScaffold_removes_owned_root_harness_and_writes_sf_harness", () => {
	const root = makeProject();
	writeLegacyPendingScaffold(root, "harness/specs/bootstrap.md");

	ensureAgenticDocsScaffold(root);

	assert.equal(existsSync(join(root, "harness")), false);
	assert.equal(existsSync(join(root, ".sf/harness/specs/bootstrap.md")), true);
});

test("ensureAgenticDocsScaffold_removes_unmarked_generated_root_harness", () => {
	const root = makeProject();
	const target = join(root, "harness/specs/bootstrap.md");
	mkdirSync(dirname(target), { recursive: true });
	writeFileSync(
		target,
		`# Bootstrap Spec: Agent Legibility

Verifies that this repo is minimally agent-legible.

## Criteria

- [ ] \`AGENTS.md\` exists at repo root and is non-empty.
- [ ] \`ARCHITECTURE.md\` exists at repo root and is non-empty.
- [ ] \`docs/exec-plans/active/\` exists.
- [ ] \`docs/exec-plans/tech-debt-tracker.md\` exists.
- [ ] \`docs/design-docs/ADR-TEMPLATE.md\` exists.

## Verification command

\`\`\`bash
for f in AGENTS.md ARCHITECTURE.md docs/exec-plans/active/index.md docs/exec-plans/tech-debt-tracker.md docs/design-docs/ADR-TEMPLATE.md .sf/harness/specs/bootstrap.md; do [ -s "$f" ] && echo "OK: $f" || echo "MISSING: $f"; done
\`\`\`

All lines should start with \`OK:\` for the bootstrap spec to pass.
`,
		"utf-8",
	);

	ensureAgenticDocsScaffold(root);

	assert.equal(existsSync(join(root, "harness")), false);
	assert.equal(existsSync(join(root, ".sf/harness/specs/bootstrap.md")), true);
});

test("checkScaffoldFreshness_when_only_markerless_scaffold_exists_does_not_warn", () => {
	const root = makeProject();
	for (const file of SCAFFOLD_FILES) {
		const target = join(root, file.path);
		mkdirSync(dirname(target), { recursive: true });
		writeFileSync(target, file.content, "utf-8");
	}

	assert.equal(checkScaffoldFreshness(root), null);
});
