/**
 * util/version-preflight.mjs — FRAMEWORK-BUG-017 (rung 2 of 3).
 *
 * Pure helper for cmds that depend on a flag / behavior introduced in a
 * specific framework version. When the installed kernel predates that
 * version, returning a structured `version_drift` envelope is strictly
 * better than the silent infra-backoff loop that bit us in
 * FRAMEWORK-BUG-010.
 *
 * Scope (Codex review edit 1): this is a **future-guard** for the next
 * framework fix that introduces a new flag. A stale 0.6.6 install
 * obviously cannot execute 0.6.8 preflight code (the helper doesn't
 * exist there). The actual catch-point for already-stale installs is
 * the route-side `detectSourceWorkspaceDrift`. This helper makes the
 * NEXT bug bundle cheaper to ship safely.
 */

import { compareVersions, SEMVER_RE } from './semver.mjs'

/**
 * Preflight check: is the installed kernel new enough to support the
 * named feature?
 *
 * - Returns `null` when the install is at-or-above `introducedIn` (pass).
 * - Returns `null` when `installedVersion` is malformed (fail-open — a
 *   corrupted `package.json` shouldn't lock users out of every cmd; the
 *   route-level drift check still catches the same install via the
 *   version mismatch path).
 * - Returns a `version_drift` error envelope when the install predates
 *   `introducedIn`. Callers `exitWith(envelope, 1)`.
 *
 * @param {Object} args
 * @param {string} args.feature  Short name of the feature being gated.
 * @param {string} args.introducedIn  Minimum framework version that ships the feature.
 * @param {string} args.installedVersion  The installed kernel's version.
 * @param {string} args.missingFlag  The CLI flag that requires this version (e.g. '--payload-file').
 * @returns {null | {
 *   status: 'error',
 *   command: 'version-preflight',
 *   error_code: 'version_drift',
 *   feature: string,
 *   introduced_in: string,
 *   installed_version: string,
 *   missing_flag: string,
 *   reason: string,
 * }}
 */
export function requireMinVersion({ feature, introducedIn, installedVersion, missingFlag }) {
	if (!installedVersion || typeof installedVersion !== 'string') return null
	if (!SEMVER_RE.test(installedVersion)) return null
	if (!SEMVER_RE.test(introducedIn)) return null

	if (compareVersions(installedVersion, introducedIn) >= 0) return null

	return {
		status: 'error',
		command: 'version-preflight',
		error_code: 'version_drift',
		feature,
		introduced_in: introducedIn,
		installed_version: installedVersion,
		missing_flag: missingFlag,
		reason: `cmd needs feature ${feature} introduced in version ${introducedIn}; installed version is ${installedVersion} — run /apt:update`,
	}
}
