import { r as toErrorObject } from "./error-coercion-CrJRoLe1.js";
import { g as registerSecretValueForRedaction } from "./redact-ClDPSbEB.js";
import "./errors-DMsu67n4.js";
import { l as secretRefKey } from "./ref-contract-BMCv3f1H.js";
import { a as describeSecretResolutionError, c as isSecretResolutionError, i as resolveSecretRefValuesSettledByProvider, r as resolveSecretRefValues, s as isProviderScopedSecretResolutionError } from "./resolve-BYXNOH_l.js";
import { t as applyResolvedAssignments, u as pushWarning } from "./runtime-shared-CP_3UL1o.js";
//#region src/secrets/runtime-owner-assignments.ts
/** Resolves SecretRef assignments atomically by owning runtime surface. */
function registerResolvedValuesForRedaction(resolved) {
	for (const value of resolved.values()) if (typeof value === "string") registerSecretValueForRedaction(value);
}
function assignmentOwnerKey(assignment) {
	return `${assignment.ownerKind}\0${assignment.ownerId}`;
}
function groupAssignmentsByOwner(assignments) {
	const groups = /* @__PURE__ */ new Map();
	for (const assignment of assignments) {
		const key = assignmentOwnerKey(assignment);
		const group = groups.get(key);
		if (group) {
			const owner = group[0];
			if (owner.requiredForGateway !== assignment.requiredForGateway || owner.disposition !== assignment.disposition) throw new Error(`Secret owner ${assignment.ownerKind}:${assignment.ownerId} has conflicting assignment policy.`);
			group.push(assignment);
			continue;
		}
		groups.set(key, [assignment]);
	}
	return [...groups.values()];
}
function createDegradedOwner(assignments, reason) {
	const owner = assignments[0];
	if (owner.ownerKind === "unknown") throw new Error(`Secret assignment ${owner.path} has no runtime owner.`);
	return {
		ownerKind: owner.ownerKind,
		ownerId: owner.ownerId,
		state: "unavailable",
		paths: assignments.map((assignment) => assignment.path),
		refKeys: assignments.map((assignment) => secretRefKey(assignment.ref)),
		reason
	};
}
/** Emits the canonical warning for one isolated runtime secret owner. */
function warnDegradedSecretOwner(context, owner) {
	pushWarning(context, {
		code: "SECRETS_OWNER_UNAVAILABLE",
		path: owner.paths[0],
		message: `Secret owner ${owner.ownerKind}:${owner.ownerId} is configured-unavailable; paths: ${owner.paths.join(", ")}; reason: ${owner.reason}.`
	});
}
async function resolveStrictAssignments(params) {
	const resolved = await resolveSecretRefValues(params.assignments.map((assignment) => assignment.ref), params.options);
	registerResolvedValuesForRedaction(resolved);
	applyResolvedAssignments({
		assignments: params.assignments,
		resolved
	});
}
function assignmentMatchesResolutionFailure(assignment, error) {
	if (!isSecretResolutionError(error)) return false;
	if (assignment.ref.source !== error.source || assignment.ref.provider !== error.provider) return false;
	return isProviderScopedSecretResolutionError(error) || assignment.ref.id.trim() === error.refId;
}
function assertOwnerCanBeIsolated(assignments, error) {
	const owner = assignments[0];
	const reason = describeSecretResolutionError(error);
	if (!reason || owner.ownerKind === "unknown" || owner.requiredForGateway || owner.disposition === "fail-closed") throw error;
	return reason;
}
async function resolveAndApplySecretAssignments(params) {
	if (!params.allowOwnerIsolation) {
		await resolveStrictAssignments(params);
		return [];
	}
	const degradedOwners = [];
	let pendingOwners = groupAssignmentsByOwner(params.assignments);
	while (pendingOwners.length > 0) {
		const resolution = await resolveSecretRefValuesSettledByProvider(pendingOwners.flat().map((assignment) => assignment.ref), params.options);
		registerResolvedValuesForRedaction(resolution.resolved);
		const failedOwners = /* @__PURE__ */ new Map();
		for (const failure of resolution.failures) {
			const matchingOwners = pendingOwners.filter((assignments) => assignments.some((assignment) => assignmentMatchesResolutionFailure(assignment, failure.error)));
			if (matchingOwners.length === 0) throw failure.error;
			for (const assignments of matchingOwners) if (!failedOwners.has(assignments)) failedOwners.set(assignments, assertOwnerCanBeIsolated(assignments, failure.error));
		}
		const nextPendingOwners = [];
		for (const assignments of pendingOwners) {
			const failureReason = failedOwners.get(assignments);
			if (failureReason) {
				for (const assignment of assignments) assignment.apply({ ...assignment.ref });
				const degradedOwner = createDegradedOwner(assignments, failureReason);
				degradedOwners.push(degradedOwner);
				warnDegradedSecretOwner(params.context, degradedOwner);
				continue;
			}
			if (assignments.every((assignment) => resolution.resolved.has(secretRefKey(assignment.ref)))) {
				applyResolvedAssignments({
					assignments,
					resolved: resolution.resolved
				});
				continue;
			}
			nextPendingOwners.push(assignments);
		}
		if (nextPendingOwners.length === pendingOwners.length) throw toErrorObject(resolution.failures[0]?.error, "Secret resolution made no progress.");
		pendingOwners = nextPendingOwners;
	}
	return degradedOwners;
}
//#endregion
export { warnDegradedSecretOwner as n, resolveAndApplySecretAssignments as t };
