import { resetTransientRetryState } from "./agent-end-recovery.js";

export async function resumeAutoAfterProviderDelay(pi, ctx, deps = null) {
	const { getAutoCommandContext, getAutoDashboardData, startAuto } =
		await import("../auto.js");
	const _deps = deps ?? {
		getSnapshot: () => getAutoDashboardData(),
		resetTransientRetryState,
		getCommandContext: () => getAutoCommandContext(),
		startAuto,
	};
	const snapshot = _deps.getSnapshot();
	if (snapshot.active) return "already-active";
	if (!snapshot.paused) return "not-paused";
	if (!snapshot.basePath) {
		ctx.ui.notify(
			"Provider error recovery delay elapsed, but no paused autonomous mode base path was available. Leaving autonomous mode paused.",
			"warning",
		);
		return "missing-base";
	}
	const commandCtx =
		typeof ctx.newSession === "function"
			? ctx
			: (_deps.getCommandContext?.() ?? null);
	if (!commandCtx || typeof commandCtx.newSession !== "function") {
		ctx.ui.notify(
			"Provider error recovery delay elapsed, but no command context with newSession was available. Leaving autonomous mode paused.",
			"warning",
		);
		return "missing-command-context";
	}
	// Reset the transient retry counter before restarting — without this,
	// consecutiveTransientCount accumulates across pause/resume cycles and
	// permanently locks out scheduled resume after MAX_TRANSIENT_AUTO_RESUMES errors.
	_deps.resetTransientRetryState();
	await _deps.startAuto(commandCtx, pi, snapshot.basePath, false, {
		step: snapshot.stepMode,
	});
	return "resumed";
}
