/**
 * @internal
 * G8 consistency-check — blocking gate for `apt:ship` (C15).
 *
 * Runs the full C15 cross-artifact consistency validator at stage 'ship'.
 * Maps the envelope to a gate verdict:
 *   - errors === 0  -> pass  (warnings never fail ship)
 *   - errors  >  0  -> fail
 *
 * `inputs` lists all five artifact paths so the C2 gate cache invalidates
 * only when one of them actually changes.
 */

import { join } from 'node:path'

import { checkConsistency } from '../../consistency/check.mjs'
// Ensure rules self-register before checkConsistency runs.
import '../../consistency/rules/index.mjs'
import { registerGate } from '../registry.mjs'

const gate = {
	id: 'consistency-check',
	description: 'Cross-artifact consistency (spec/plan/review/qa/progress) has no error drift.',
	severity: 'blocking',
	skills: ['ship'],
	applies_to_profile: (ctx) => ctx.profile === 'full-pipeline',
	async check(ctx) {
		const inputs = [
			join(ctx.taskDir, 'spec.md'),
			join(ctx.taskDir, 'implementation_plan.json'),
			join(ctx.taskDir, 'review.json'),
			join(ctx.taskDir, 'qa_signoff.json'),
			join(ctx.taskDir, 'build-progress.json'),
		]
		const env = await checkConsistency({ taskDir: ctx.taskDir, stage: 'ship' })
		if (env.errors === 0) {
			return {
				status: 'pass',
				reason: `${env.rules.length} rule(s) clean (${env.warnings} warning(s))`,
				evidence: { errors: env.errors, warnings: env.warnings },
				inputs,
			}
		}
		const failing = env.rules
			.filter((r) => r.status === 'fail' && r.severity === 'error')
			.map((r) => r.id)
		return {
			status: 'fail',
			reason: `${env.errors} error-severity consistency drift (${failing.join(', ')})`,
			evidence: {
				errors: env.errors,
				warnings: env.warnings,
				failing_rules: failing,
			},
			inputs,
		}
	},
}

registerGate(gate)
export default gate
