/**
 * @internal
 * consistency/rules/r5-verdict-consistency.mjs — R5 (C15).
 *
 * Fails when:
 *   - qa.verdict === 'approved' AND review has >=1 unresolved critical finding
 *   - qa.verdict === 'rejected' AND qa has no findings at all AND review has
 *     zero unresolved findings (rejected-without-evidence)
 *
 * `approved-with-notes` is the escape hatch — passes regardless of unresolved
 * criticals in review.json.
 *
 * Severity: error. Stages: verify, ship.
 */

import { registerRule } from '../registry.mjs'

const rule = {
	id: 'r5-verdict-consistency',
	severity: 'error',
	stages: ['verify', 'ship'],
	description: 'qa_signoff verdict is consistent with review evidence.',
	async check({ parsed }) {
		if (!parsed?.qa?.present) {
			return { status: 'skip', drift: [], reason: 'qa_signoff.json not present' }
		}
		const verdict = parsed.qa.verdict ?? 'unknown'
		const reviewFindings = parsed?.review?.findings ?? []
		const unresolvedCritical = reviewFindings.filter(
			(f) => f.severity === 'critical' && f.status !== 'fixed',
		)
		if (verdict === 'approved' && unresolvedCritical.length > 0) {
			return {
				status: 'fail',
				drift: [
					{
						verdict,
						blockers: unresolvedCritical.map((f) => ({
							id: f.id,
							title: f.title,
						})),
						reason: 'approved verdict with unresolved critical finding(s)',
					},
				],
				reason: `approved verdict contradicts ${unresolvedCritical.length} unresolved critical finding(s)`,
			}
		}
		if (verdict === 'rejected') {
			const qaFindings = parsed.qa.findings ?? []
			const anyUnresolvedReview = reviewFindings.some((f) => f.status !== 'fixed')
			if (qaFindings.length === 0 && !anyUnresolvedReview) {
				return {
					status: 'fail',
					drift: [
						{
							verdict,
							blockers: [],
							reason: 'rejected verdict without any cited findings',
						},
					],
					reason: 'rejected verdict has no supporting findings',
				}
			}
		}
		return {
			status: 'pass',
			drift: [],
			reason: `verdict ${verdict} is consistent with review evidence`,
		}
	},
}

registerRule(rule)
export default rule
