/**
 * Pause autonomous mode due to a provider error.
 *
 * For transient errors (rate limits, server errors, overloaded), schedules
 * an automatic resume after a delay. For permanent errors (auth, billing),
 * pauses indefinitely — user must manually resume.
 */
import { NOTICE_KIND } from "./notification-store.js";

export async function pauseAutoForProviderError(
	ui,
	errorDetail,
	pause,
	options,
) {
	const shouldAutoResume =
		(options?.isRateLimit || options?.isTransient) &&
		options.retryAfterMs &&
		options.retryAfterMs > 0 &&
		options.resume;
	if (shouldAutoResume) {
		const delaySec = Math.ceil(options.retryAfterMs / 1000);
		const reason = options.isRateLimit
			? "Rate limited"
			: "Server error (transient)";
		ui.notify(
			`${reason}${errorDetail}. Resuming automatically in ${delaySec}s...`,
			"warning",
			{
				noticeKind: NOTICE_KIND.TOOL_NOTICE,
				dedupe_key: `provider-error-auto-resume:${options.isRateLimit ? "rate" : "transient"}`,
			},
		);
		await pause();
		// Schedule resume after the delay.
		setTimeout(() => {
			const resumeMsg = options.isRateLimit
				? "Rate limit window elapsed. Resuming autonomous mode."
				: "Server error recovery delay elapsed. Resuming autonomous mode.";
			ui.notify(resumeMsg, "info", {
				noticeKind: NOTICE_KIND.SYSTEM_NOTICE,
				dedupe_key: "provider-error-scheduled-resume",
			});
			options.resume();
		}, options.retryAfterMs);
	} else {
		ui.notify(
			`Autonomous mode paused due to provider error${errorDetail}`,
			"warning",
			{
				noticeKind: NOTICE_KIND.BLOCKING_NOTICE,
				dedupe_key: `provider-pause:${String(errorDetail).slice(0, 120)}`,
			},
		);
		await pause();
	}
}
