/**
 * verification-defer-policy.test.mjs — auto-defer classification contracts.
 *
 * Purpose: keep autonomous verification from retrying low-risk style findings
 * while still blocking real test/build/runtime failures.
 */
import assert from "node:assert/strict";
import { test } from "vitest";
import {
	classifyCheck,
	computeDeferConfidence,
	decideAutoDefer,
} from "../verification-defer-policy.js";

function result(checks) {
	return { checks };
}

test("decideAutoDefer_when_all_failures_are_style_only_defers_above_threshold", () => {
	const decision = decideAutoDefer(
		result([
			{
				command: "npx biome format --write src",
				exitCode: 1,
				stderr: "formatting changed",
			},
		]),
	);

	assert.equal(decision.defer, true);
	assert.equal(decision.confidence, 0.9);
	assert.deepEqual(decision.reasons, [
		"npx biome format --write src: deferrable",
	]);
});

test("decideAutoDefer_when_failure_contains_error_blocks_even_for_lint_command", () => {
	const check = {
		command: "eslint --fix src",
		exitCode: 1,
		stderr: "Parsing error: Unexpected token",
	};

	assert.equal(classifyCheck(check), "blocking");
	assert.deepEqual(decideAutoDefer(result([check])), {
		defer: false,
		confidence: 0,
		reasons: [],
	});
});

test("computeDeferConfidence_when_deferrable_and_unknown_stays_below_default_threshold", () => {
	const confidence = computeDeferConfidence(
		result([
			{
				command: "prettier --check .",
				exitCode: 1,
				stderr: "Code style issues found",
			},
			{
				command: "custom verify",
				exitCode: 2,
				stderr: "review output manually",
			},
		]),
	);

	assert.equal(confidence, 0.7);
	assert.equal(
		decideAutoDefer(
			result([
				{
					command: "prettier --check .",
					exitCode: 1,
					stderr: "Code style issues found",
				},
				{
					command: "custom verify",
					exitCode: 2,
					stderr: "review output manually",
				},
			]),
		).defer,
		false,
	);
});

test("decideAutoDefer_when_blocking_failure_present_does_not_defer", () => {
	assert.equal(
		decideAutoDefer(
			result([
				{ command: "lint", exitCode: 1, stderr: "style warning" },
				{
					command: "test",
					exitCode: 1,
					stderr: "fatal error: assertion failed",
				},
			]),
		).defer,
		false,
	);
});
