import assert from "node:assert/strict";
import { test } from "vitest";

import {
	reorderAndSplitForCaching,
	reorderForCaching,
} from "../prompt-ordering.js";

test("reorderForCaching_when_inlined_slice_summary_has_requirements_advanced_keeps_it_after_mission", () => {
	const prompt = [
		"# Milestone Validation",
		"",
		"## Working Directory",
		"/repo",
		"",
		"## Mission",
		"Dispatch reviewers.",
		"",
		"## Context",
		"Inlined below.",
		"",
		"## Inlined Context",
		"### S01 Summary",
		"# S01",
		"",
		"## Requirements Advanced",
		"- R1",
		"",
		"## Requirements Validated",
		"None.",
	].join("\n");

	const reordered = reorderForCaching(prompt);

	assert.ok(
		reordered.indexOf("## Mission") <
			reordered.indexOf("## Requirements Advanced"),
	);
	assert.ok(
		reordered.indexOf("## Context") <
			reordered.indexOf("## Requirements Advanced"),
	);
});

test("reorderForCaching_when_top_level_requirements_exists_still_hoists_exact_requirements_block", () => {
	const prompt = [
		"# Execute",
		"",
		"## Mission",
		"Do work.",
		"",
		"## Requirements",
		"- R1",
		"",
		"## Verification",
		"Run tests.",
	].join("\n");

	const reordered = reorderForCaching(prompt);

	assert.ok(
		reordered.indexOf("## Requirements") < reordered.indexOf("## Mission"),
	);
});

test("reorderAndSplitForCaching_when_prompt_has_dynamic_section_returns_split", () => {
	const prompt = [
		"Preamble text.",
		"",
		"## Working Directory",
		"/repo",
		"",
		"## Requirements",
		"- R1",
		"",
		"## Inlined Task Plan",
		"Task: do something.",
	].join("\n");

	const result = reorderAndSplitForCaching(prompt);

	assert.ok(result !== null, "expected non-null split result");
	assert.ok(
		result.before.includes("## Working Directory"),
		"before should have static section",
	);
	assert.ok(
		result.before.includes("## Requirements"),
		"before should have semi-static section",
	);
	assert.ok(
		result.after.includes("## Inlined Task Plan"),
		"after should have dynamic section",
	);
	assert.ok(
		!result.before.includes("## Inlined Task Plan"),
		"before should not have dynamic section",
	);
});

test("reorderAndSplitForCaching_when_no_dynamic_sections_returns_null", () => {
	const prompt = [
		"## Working Directory",
		"/repo",
		"",
		"## Requirements",
		"- R1",
	].join("\n");

	const result = reorderAndSplitForCaching(prompt);
	assert.strictEqual(result, null, "expected null when no dynamic sections");
});

test("reorderAndSplitForCaching_preamble_goes_into_before", () => {
	const prompt = [
		"System instructions here.",
		"",
		"## Decisions",
		"- D1",
		"",
		"## Resume State",
		"Task was paused.",
	].join("\n");

	const result = reorderAndSplitForCaching(prompt);

	assert.ok(result !== null);
	assert.ok(
		result.before.includes("System instructions here."),
		"preamble should be in before",
	);
	assert.ok(
		result.after.includes("## Resume State"),
		"dynamic section in after",
	);
});
