import { t as isTruthyEnvValue } from "./env-D9zNF4UR.js";
import { f as resolveHomeDir } from "./utils-FLBGJBzj.js";
import { _ as recoverConfigFromLastKnownGood, g as recoverConfigFromJsonRootSuffix, u as readConfigFileSnapshot } from "./io-6EUKoyeO.js";
import { n as formatConfigIssueLines } from "./issue-format-ltC34NBF.js";
import { t as note } from "./note-Daxss21Z.js";
import { r as noteIncludeConfinementWarning } from "./doctor-config-analysis-Cn50yq7i.js";
import { t as findDoctorLegacyConfigIssues } from "./legacy-config-issues-DHeDn8Mz.js";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/commands/doctor-config-preflight.ts
let doctorStateMigrationsPromise = null;
function loadDoctorStateMigrations() {
	doctorStateMigrationsPromise ??= import("./doctor-state-migrations-CPyQVDRA.js");
	return doctorStateMigrationsPromise;
}
async function maybeMigrateLegacyConfig() {
	const changes = [];
	const home = resolveHomeDir();
	if (!home) return changes;
	const targetDir = path.join(home, ".nodmix");
	const targetPath = path.join(targetDir, "nodmix.json");
	try {
		await fs.access(targetPath);
		return changes;
	} catch {}
	const legacyCandidates = [path.join(home, ".clawdbot", "clawdbot.json")];
	let legacyPath = null;
	for (const candidate of legacyCandidates) try {
		await fs.access(candidate);
		legacyPath = candidate;
		break;
	} catch {}
	if (!legacyPath) return changes;
	await fs.mkdir(targetDir, { recursive: true });
	try {
		await fs.copyFile(legacyPath, targetPath, fs.constants.COPYFILE_EXCL);
		changes.push(`Migrated legacy config: ${legacyPath} -> ${targetPath}`);
	} catch {}
	return changes;
}
function collectDoctorLegacyIssues(snapshot) {
	if (!snapshot.exists) return [];
	const resolvedRaw = snapshot.sourceConfig ?? snapshot.config ?? {};
	return findDoctorLegacyConfigIssues(resolvedRaw, snapshot.parsed ?? resolvedRaw);
}
function addDoctorLegacyIssues(snapshot) {
	const legacyIssues = collectDoctorLegacyIssues(snapshot);
	if (legacyIssues.length === 0) return snapshot;
	return {
		...snapshot,
		legacyIssues
	};
}
function shouldSkipPluginValidationForDoctorConfigPreflight(env = process.env) {
	return isTruthyEnvValue(env.NODMIX_UPDATE_IN_PROGRESS);
}
function noteStateMigrationResult(result) {
	if (result.changes.length > 0) note(result.changes.map((entry) => `- ${entry}`).join("\n"), "Doctor changes");
	if (result.warnings.length > 0) note(result.warnings.map((entry) => `- ${entry}`).join("\n"), "Doctor warnings");
}
async function runDoctorConfigPreflight(options = {}) {
	if (options.migrateState !== false) {
		const { autoMigrateLegacyStateDir } = await loadDoctorStateMigrations();
		noteStateMigrationResult(await autoMigrateLegacyStateDir({ env: process.env }));
	}
	if (options.migrateLegacyConfig !== false) {
		const legacyConfigChanges = await maybeMigrateLegacyConfig();
		if (legacyConfigChanges.length > 0) note(legacyConfigChanges.map((entry) => `- ${entry}`).join("\n"), "Doctor changes");
	}
	const readOptions = { skipPluginValidation: shouldSkipPluginValidationForDoctorConfigPreflight() };
	let snapshot = addDoctorLegacyIssues(await readConfigFileSnapshot(readOptions));
	if (options.repairPrefixedConfig === true && snapshot.exists && !snapshot.valid) {
		if (await recoverConfigFromJsonRootSuffix(snapshot)) {
			note("Removed non-JSON prefix from nodmix.json; original saved as .clobbered.*.", "Config");
			snapshot = addDoctorLegacyIssues(await readConfigFileSnapshot(readOptions));
		} else if (await recoverConfigFromLastKnownGood({
			snapshot,
			reason: "doctor-invalid-config"
		})) {
			note("Restored nodmix.json from last-known-good; original saved as .clobbered.*.", "Config");
			snapshot = addDoctorLegacyIssues(await readConfigFileSnapshot(readOptions));
		}
	}
	const invalidConfigNote = options.invalidConfigNote ?? "Config invalid; doctor will run with best-effort config.";
	if (invalidConfigNote && snapshot.exists && !snapshot.valid && snapshot.legacyIssues.length === 0) {
		note(invalidConfigNote, "Config");
		noteIncludeConfinementWarning(snapshot);
	}
	const warnings = snapshot.warnings ?? [];
	if (warnings.length > 0) note(formatConfigIssueLines(warnings, "-").join("\n"), "Config warnings");
	const baseConfig = snapshot.sourceConfig ?? snapshot.config ?? {};
	if (options.migrateState !== false) {
		const { autoMigrateLegacyState, autoMigrateLegacyTaskStateSidecars } = await loadDoctorStateMigrations();
		noteStateMigrationResult(snapshot.valid ? await autoMigrateLegacyState({
			cfg: baseConfig,
			env: process.env
		}) : await autoMigrateLegacyTaskStateSidecars({ env: process.env }));
	}
	return {
		snapshot,
		baseConfig
	};
}
//#endregion
export { shouldSkipPluginValidationForDoctorConfigPreflight as n, runDoctorConfigPreflight as t };
