import { tl as resolvePluginInstallDir } from "./env-Dlz8aQHP.js";

//#region src/plugins/installs.ts
function buildNpmResolutionInstallFields(resolution) {
	return {
		resolvedName: resolution?.name,
		resolvedVersion: resolution?.version,
		resolvedSpec: resolution?.resolvedSpec,
		integrity: resolution?.integrity,
		shasum: resolution?.shasum,
		resolvedAt: resolution?.resolvedAt
	};
}
function recordPluginInstall(cfg, update) {
	const { pluginId, ...record } = update;
	const installs = {
		...cfg.plugins?.installs,
		[pluginId]: {
			...cfg.plugins?.installs?.[pluginId],
			...record,
			installedAt: record.installedAt ?? (/* @__PURE__ */ new Date()).toISOString()
		}
	};
	return {
		...cfg,
		plugins: {
			...cfg.plugins,
			installs: {
				...installs,
				[pluginId]: installs[pluginId]
			}
		}
	};
}
function repairUpdateOwnedPluginInstallState(cfg, options = {}) {
	const installs = cfg.plugins?.installs;
	if (!installs || Object.keys(installs).length === 0) return {
		config: cfg,
		changed: false,
		changes: [],
		warnings: [],
		repairedPluginIds: []
	};
	const resolveNpmInstallPath = options.resolveNpmInstallPath ?? resolvePluginInstallDir;
	const nextInstalls = { ...installs };
	const changes = [];
	const warnings = [];
	const repairedPluginIds = [];
	for (const [pluginId, record] of Object.entries(installs).toSorted(([left], [right]) => left.localeCompare(right))) {
		if (record.source !== "npm") continue;
		if (!record.spec?.trim()) {
			warnings.push(`Skipped npm install record repair for "${pluginId}": missing npm spec.`);
			continue;
		}
		if (record.installPath?.trim()) continue;
		let installPath;
		try {
			installPath = resolveNpmInstallPath(pluginId);
		} catch (err) {
			warnings.push(`Skipped npm install record repair for "${pluginId}": ${err instanceof Error ? err.message : String(err)}`);
			continue;
		}
		nextInstalls[pluginId] = {
			...record,
			installPath
		};
		repairedPluginIds.push(pluginId);
		changes.push(`Repaired npm install record for "${pluginId}" with install path ${installPath}.`);
	}
	if (repairedPluginIds.length === 0) return {
		config: cfg,
		changed: false,
		changes,
		warnings,
		repairedPluginIds
	};
	return {
		config: {
			...cfg,
			plugins: {
				...cfg.plugins,
				installs: nextInstalls
			}
		},
		changed: true,
		changes,
		warnings,
		repairedPluginIds
	};
}

//#endregion
export { recordPluginInstall as n, repairUpdateOwnedPluginInstallState as r, buildNpmResolutionInstallFields as t };