import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, it } from "vitest";
import { extractSection } from "../files.ts";

const __dirname = dirname(fileURLToPath(import.meta.url));
const templatesDir = join(__dirname, "..", "templates");
const promptsDir = join(__dirname, "..", "prompts");

function loadTemplate(name: string): string {
	return readFileSync(join(templatesDir, `${name}.md`), "utf-8");
}

function loadPrompt(name: string): string {
	return readFileSync(join(promptsDir, `${name}.md`), "utf-8");
}

describe("Level 1: Templates contain quality gate headings", () => {
	it("plan.md contains ## Threat Surface", () => {
		const plan = loadTemplate("plan");
		assert.ok(plan.includes("## Threat Surface"));
	});

	it("plan.md contains ## Requirement Impact", () => {
		const plan = loadTemplate("plan");
		assert.ok(plan.includes("## Requirement Impact"));
	});

	it("task-plan.md contains ## Failure Modes", () => {
		const taskPlan = loadTemplate("task-plan");
		assert.ok(taskPlan.includes("## Failure Modes"));
	});

	it("task-plan.md contains ## Load Profile", () => {
		const taskPlan = loadTemplate("task-plan");
		assert.ok(taskPlan.includes("## Load Profile"));
	});

	it("task-plan.md contains ## Negative Tests", () => {
		const taskPlan = loadTemplate("task-plan");
		assert.ok(taskPlan.includes("## Negative Tests"));
	});

	it("slice-summary.md contains ## Operational Readiness", () => {
		const sliceSummary = loadTemplate("slice-summary");
		assert.ok(sliceSummary.includes("## Operational Readiness"));
	});

	it("roadmap.md contains ## Horizontal Checklist", () => {
		const roadmap = loadTemplate("roadmap");
		assert.ok(roadmap.includes("## Horizontal Checklist"));
	});

	it("milestone-summary.md contains ## Decision Re-evaluation", () => {
		const milestoneSummary = loadTemplate("milestone-summary");
		assert.ok(milestoneSummary.includes("## Decision Re-evaluation"));
	});
});

describe("Level 2: Prompts reference quality gates", () => {
	it("plan-slice.md mentions Threat Surface", () => {
		const planSlice = loadPrompt("plan-slice");
		assert.ok(planSlice.includes("Threat Surface"));
	});

	it("plan-slice.md mentions Requirement Impact", () => {
		const planSlice = loadPrompt("plan-slice");
		assert.ok(planSlice.includes("Requirement Impact"));
	});

	it("plan-slice.md mentions quality gate", () => {
		const planSlice = loadPrompt("plan-slice");
		assert.ok(planSlice.toLowerCase().includes("quality gate"));
	});

	it("guided-plan-slice.md mentions Threat Surface or Q3", () => {
		const guidedPlanSlice = loadPrompt("guided-plan-slice");
		assert.ok(
			guidedPlanSlice.includes("Threat Surface") ||
				guidedPlanSlice.includes("Q3"),
		);
	});

	it("execute-task.md mentions Failure Modes", () => {
		const executeTask = loadPrompt("execute-task");
		assert.ok(executeTask.includes("Failure Modes"));
	});

	it("execute-task.md mentions Load Profile", () => {
		const executeTask = loadPrompt("execute-task");
		assert.ok(executeTask.includes("Load Profile"));
	});

	it("execute-task.md mentions Negative Tests", () => {
		const executeTask = loadPrompt("execute-task");
		assert.ok(executeTask.includes("Negative Tests"));
	});

	it("guided-execute-task.md mentions Failure Modes or Q5", () => {
		const guidedExecuteTask = loadPrompt("guided-execute-task");
		assert.ok(
			guidedExecuteTask.includes("Failure Modes") ||
				guidedExecuteTask.includes("Q5"),
		);
	});

	it("complete-slice.md mentions Operational Readiness", () => {
		const completeSlice = loadPrompt("complete-slice");
		assert.ok(completeSlice.includes("Operational Readiness"));
	});

	it("guided-complete-slice.md mentions Operational Readiness or Q8", () => {
		const guidedCompleteSlice = loadPrompt("guided-complete-slice");
		assert.ok(
			guidedCompleteSlice.includes("Operational Readiness") ||
				guidedCompleteSlice.includes("Q8"),
		);
	});

	it("complete-milestone.md mentions Horizontal Checklist", () => {
		const completeMilestone = loadPrompt("complete-milestone");
		assert.ok(completeMilestone.includes("Horizontal Checklist"));
	});

	it("complete-milestone.md mentions Decision Re-evaluation", () => {
		const completeMilestone = loadPrompt("complete-milestone");
		assert.ok(completeMilestone.includes("Decision Re-evaluation"));
	});

	it("plan-milestone.md mentions horizontal checklist", () => {
		const planMilestone = loadPrompt("plan-milestone");
		assert.ok(planMilestone.toLowerCase().includes("horizontal checklist"));
	});

	it("guided-plan-milestone.md mentions Horizontal Checklist", () => {
		const guidedPlanMilestone = loadPrompt("guided-plan-milestone");
		assert.ok(guidedPlanMilestone.includes("Horizontal Checklist"));
	});

	it("reassess-roadmap.md mentions Threat Surface", () => {
		const reassess = loadPrompt("reassess-roadmap");
		assert.ok(reassess.includes("Threat Surface"));
	});

	it("reassess-roadmap.md mentions Operational Readiness", () => {
		const reassess = loadPrompt("reassess-roadmap");
		assert.ok(reassess.includes("Operational Readiness"));
	});

	it("reassess-roadmap.md mentions Horizontal Checklist", () => {
		const reassess = loadPrompt("reassess-roadmap");
		assert.ok(reassess.includes("Horizontal Checklist"));
	});

	it("replan-slice.md mentions Threat Surface", () => {
		const replan = loadPrompt("replan-slice");
		assert.ok(replan.includes("Threat Surface"));
	});
});

describe("Level 3: Parser backward compatibility — extractSection handles new headings", () => {
	it("extractSection returns null for Threat Surface on old plan", () => {
		const oldPlan = `# S01: Auth Flow

## Must-Haves

- Login form works

## Proof Level

## Tasks

- [ ] **T01: Build login** \`est:1h\`
`;
		assert.strictEqual(extractSection(oldPlan, "Threat Surface"), null);
	});

	it("extractSection returns null for Requirement Impact on old plan", () => {
		const oldPlan = `# S01: Auth Flow

## Must-Haves

- Login form works

## Proof Level

## Tasks

- [ ] **T01: Build login** \`est:1h\`
`;
		assert.strictEqual(extractSection(oldPlan, "Requirement Impact"), null);
	});

	it("extractSection still parses Must-Haves on old plan", () => {
		const oldPlan = `# S01: Auth Flow

## Must-Haves

- Login form works

## Proof Level

## Tasks

- [ ] **T01: Build login** \`est:1h\`
`;
		const mustHaves = extractSection(oldPlan, "Must-Haves");
		assert.ok(mustHaves !== null && mustHaves.includes("Login form works"));
	});

	it("extractSection extracts Threat Surface content from new plan", () => {
		const newPlan = `# S01: Auth Flow

## Must-Haves

- Login form works

## Threat Surface

- **Abuse**: Credential stuffing

## Proof Level

## Tasks

- [ ] **T01: Build login** \`est:1h\`
`;
		const threatSurface = extractSection(newPlan, "Threat Surface");
		assert.ok(threatSurface !== null && threatSurface.includes("Credential stuffing"));
	});

	it("extractSection extracts Requirement Impact content from new plan", () => {
		const newPlan = `# S01: Auth Flow

## Must-Haves

- Login form works

## Requirement Impact

- **Requirements touched**: R001

## Proof Level

## Tasks

- [ ] **T01: Build login** \`est:1h\`
`;
		const reqImpact = extractSection(newPlan, "Requirement Impact");
		assert.ok(reqImpact !== null && reqImpact.includes("R001"));
	});

	it("extractSection extracts Failure Modes from new task plan", () => {
		const newTaskPlan = `# T01: Build Login

## Description

Build the login endpoint.

## Failure Modes

| Dependency | On error |

## Steps

1. Create route
`;
		const failureModes = extractSection(newTaskPlan, "Failure Modes");
		assert.ok(failureModes !== null && failureModes.includes("Dependency"));
	});

	it("extractSection extracts Operational Readiness from new summary", () => {
		const newSummary = `# S01: Auth Flow

**Built login with session management**

## Verification

All tests pass.

## Operational Readiness

- **Health signal**: /health endpoint

## Deviations

None.
`;
		const opReadiness = extractSection(newSummary, "Operational Readiness");
		assert.ok(opReadiness !== null && opReadiness.includes("/health endpoint"));
	});
});

describe("Level 4: Template section ordering is correct", () => {
	it("plan.md: Threat Surface is between Must-Haves and Proof Level", () => {
		const plan = loadTemplate("plan");
		const mustHavesIdx = plan.indexOf("## Must-Haves");
		const threatIdx = plan.indexOf("## Threat Surface");
		const proofIdx = plan.indexOf("## Proof Level");
		assert.ok(mustHavesIdx < threatIdx && threatIdx < proofIdx);
	});

	it("plan.md: Requirement Impact is between Threat Surface and Proof Level", () => {
		const plan = loadTemplate("plan");
		const threatIdx = plan.indexOf("## Threat Surface");
		const reqImpactIdx = plan.indexOf("## Requirement Impact");
		const proofIdx = plan.indexOf("## Proof Level");
		assert.ok(threatIdx < reqImpactIdx && reqImpactIdx < proofIdx);
	});

	it("task-plan.md: Failure Modes is between Description and Steps", () => {
		const taskPlan = loadTemplate("task-plan");
		const descIdx = taskPlan.indexOf("## Description");
		const failIdx = taskPlan.indexOf("## Failure Modes");
		const stepsIdx = taskPlan.indexOf("## Steps");
		assert.ok(descIdx < failIdx && failIdx < stepsIdx);
	});

	it("task-plan.md: Failure Modes < Load Profile < Negative Tests < Steps", () => {
		const taskPlan = loadTemplate("task-plan");
		const failIdx = taskPlan.indexOf("## Failure Modes");
		const loadIdx = taskPlan.indexOf("## Load Profile");
		const negIdx = taskPlan.indexOf("## Negative Tests");
		const stepsIdx = taskPlan.indexOf("## Steps");
		assert.ok(failIdx < loadIdx && loadIdx < negIdx && negIdx < stepsIdx);
	});

	it("slice-summary.md: Operational Readiness is between Requirements Invalidated and Deviations", () => {
		const sliceSummary = loadTemplate("slice-summary");
		const reqInvalidIdx = sliceSummary.indexOf("## Requirements Invalidated");
		const opIdx = sliceSummary.indexOf("## Operational Readiness");
		const devIdx = sliceSummary.indexOf("## Deviations");
		assert.ok(reqInvalidIdx < opIdx && opIdx < devIdx);
	});

	it("milestone-summary.md: Decision Re-evaluation is between Requirement Changes and Forward Intelligence", () => {
		const milestoneSummary = loadTemplate("milestone-summary");
		const reqChangesIdx = milestoneSummary.indexOf("## Requirement Changes");
		const decRevalIdx = milestoneSummary.indexOf("## Decision Re-evaluation");
		const fwdIntelIdx = milestoneSummary.indexOf("## Forward Intelligence");
		assert.ok(reqChangesIdx < decRevalIdx && decRevalIdx < fwdIntelIdx);
	});
});
