import { b as resolveCronSessionDiagnosticContext, v as formatRecoveryOutcome, y as formatStoppedCronSessionDiagnosticFields } from "./diagnostic-BKRV85sg.js";
import { t as diagnosticLogger } from "./diagnostic-runtime-DinDAg7v.js";
import { i as isDiagnosticSessionStateCurrent } from "./diagnostic-session-state-Bsxg7VEQ.js";
import { d as resolveActiveEmbeddedRunSessionId, o as isEmbeddedPiRunActive, s as isEmbeddedPiRunHandleActive, t as abortAndDrainEmbeddedPiRun, u as resolveActiveEmbeddedRunHandleSessionId } from "./runs-CZlxgr7Y.js";
import { f as resetCommandLane, o as getCommandLaneSnapshot } from "./command-queue-F_bI3sQH.js";
import { t as resolveEmbeddedSessionLane } from "./lanes-DOz5r4st.js";
//#region src/logging/diagnostic-stuck-session-recovery.runtime.ts
const STUCK_SESSION_ABORT_SETTLE_MS = 15e3;
const recoveriesInFlight = /* @__PURE__ */ new Set();
function recoveryKey(params) {
	return params.sessionKey?.trim() || params.sessionId?.trim() || void 0;
}
function formatRecoveryContext(params, extra) {
	const fields = [
		`sessionId=${params.sessionId ?? extra?.activeSessionId ?? "unknown"}`,
		`sessionKey=${params.sessionKey ?? "unknown"}`,
		`age=${Math.round(params.ageMs / 1e3)}s`,
		`queueDepth=${params.queueDepth ?? 0}`
	];
	if (extra?.activeSessionId) fields.push(`activeSessionId=${extra.activeSessionId}`);
	if (extra?.lane) fields.push(`lane=${extra.lane}`);
	if (extra?.activeCount !== void 0) fields.push(`laneActive=${extra.activeCount}`);
	if (extra?.queuedCount !== void 0) fields.push(`laneQueued=${extra.queuedCount}`);
	return fields.join(" ");
}
async function recoverStuckDiagnosticSession(params) {
	const key = recoveryKey(params);
	if (!key || recoveriesInFlight.has(key)) return {
		status: "skipped",
		action: "observe_only",
		reason: key ? "already_in_flight" : "missing_session_ref",
		sessionId: params.sessionId,
		sessionKey: params.sessionKey
	};
	recoveriesInFlight.add(key);
	try {
		if (!isDiagnosticSessionStateCurrent({
			sessionId: params.sessionId,
			sessionKey: params.sessionKey,
			generation: params.stateGeneration,
			state: "processing"
		})) return {
			status: "skipped",
			action: "observe_only",
			reason: "stale_session_state",
			sessionId: params.sessionId,
			sessionKey: params.sessionKey
		};
		const fallbackActiveSessionId = params.sessionId && isEmbeddedPiRunHandleActive(params.sessionId) ? params.sessionId : void 0;
		const activeSessionId = params.sessionKey ? resolveActiveEmbeddedRunHandleSessionId(params.sessionKey) ?? fallbackActiveSessionId : fallbackActiveSessionId;
		const activeWorkSessionId = params.sessionKey ? resolveActiveEmbeddedRunSessionId(params.sessionKey) ?? params.sessionId : params.sessionId;
		const laneKey = params.sessionKey?.trim() || params.sessionId?.trim();
		const sessionLane = laneKey ? resolveEmbeddedSessionLane(laneKey) : null;
		let aborted = false;
		let drained = true;
		let forceCleared = false;
		if (activeSessionId) {
			if (params.allowActiveAbort !== true) {
				const outcome = {
					status: "skipped",
					action: "observe_only",
					reason: "active_embedded_run",
					sessionId: params.sessionId,
					sessionKey: params.sessionKey,
					activeSessionId,
					activeWorkKind: "embedded_run"
				};
				diagnosticLogger.warn(`stuck session recovery skipped: ${formatRecoveryContext(params, { activeSessionId })}`);
				diagnosticLogger.warn(`stuck session recovery outcome: ${formatRecoveryOutcome(outcome)}`);
				return outcome;
			}
			const result = await abortAndDrainEmbeddedPiRun({
				sessionId: activeSessionId,
				sessionKey: params.sessionKey,
				settleMs: STUCK_SESSION_ABORT_SETTLE_MS,
				forceClear: true,
				reason: "stuck_recovery"
			});
			aborted = result.aborted;
			drained = result.drained;
			forceCleared = result.forceCleared;
		}
		if (!activeSessionId && activeWorkSessionId && isEmbeddedPiRunActive(activeWorkSessionId)) {
			const outcome = {
				status: "skipped",
				action: "keep_lane",
				reason: "active_reply_work",
				sessionId: params.sessionId,
				sessionKey: params.sessionKey,
				activeSessionId: activeWorkSessionId,
				activeWorkKind: "embedded_run"
			};
			diagnosticLogger.warn(`stuck session recovery outcome: ${formatRecoveryOutcome(outcome)}`);
			return outcome;
		}
		if (!activeSessionId && sessionLane) {
			const laneSnapshot = getCommandLaneSnapshot(sessionLane);
			if (laneSnapshot.activeCount > 0) {
				const outcome = {
					status: "skipped",
					action: "keep_lane",
					reason: "active_lane_task",
					sessionId: params.sessionId,
					sessionKey: params.sessionKey,
					lane: sessionLane,
					activeCount: laneSnapshot.activeCount,
					queuedCount: laneSnapshot.queuedCount
				};
				diagnosticLogger.warn(`stuck session recovery outcome: ${formatRecoveryOutcome(outcome)}`);
				return outcome;
			}
		}
		const released = sessionLane && (!activeSessionId || !aborted || !drained) ? resetCommandLane(sessionLane) : 0;
		if (aborted || released > 0) {
			const action = aborted ? "abort_embedded_run" : "release_lane";
			const stoppedFields = formatStoppedCronSessionDiagnosticFields(resolveCronSessionDiagnosticContext({
				sessionKey: params.sessionKey,
				activeSessionId
			}));
			diagnosticLogger.warn(`stuck session recovery: sessionId=${params.sessionId ?? activeSessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} age=${Math.round(params.ageMs / 1e3)}s action=${action} aborted=${aborted} drained=${drained} released=${released}${stoppedFields ? ` ${stoppedFields}` : ""}`);
			const outcome = aborted ? {
				status: "aborted",
				action: "abort_embedded_run",
				sessionId: params.sessionId,
				sessionKey: params.sessionKey,
				activeSessionId,
				activeWorkKind: "embedded_run",
				aborted,
				drained,
				forceCleared,
				released,
				lane: sessionLane ?? void 0
			} : {
				status: "released",
				action: "release_lane",
				sessionId: params.sessionId,
				sessionKey: params.sessionKey,
				released,
				lane: sessionLane ?? void 0
			};
			diagnosticLogger.warn(`stuck session recovery outcome: ${formatRecoveryOutcome(outcome)}`);
			return outcome;
		}
		const outcome = {
			status: "noop",
			action: "none",
			reason: "no_active_work",
			sessionId: params.sessionId,
			sessionKey: params.sessionKey,
			lane: sessionLane ?? void 0
		};
		diagnosticLogger.warn(`stuck session recovery outcome: ${formatRecoveryOutcome(outcome)}`);
		return outcome;
	} catch (err) {
		const outcome = {
			status: "failed",
			action: "none",
			reason: "exception",
			sessionId: params.sessionId,
			sessionKey: params.sessionKey,
			error: String(err)
		};
		diagnosticLogger.warn(`stuck session recovery failed: sessionId=${params.sessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} err=${String(err)}`);
		return outcome;
	} finally {
		recoveriesInFlight.delete(key);
	}
}
const __testing = { resetRecoveriesInFlight() {
	recoveriesInFlight.clear();
} };
//#endregion
export { __testing, recoverStuckDiagnosticSession };
