import { t } from './i18n.js';
import { CLI_VERSION } from './cli-version.js';
import { canAutoUpdateCli, installLatestGlobal, reexecCursorconnect, } from './cli-auto-update.js';
import { fetchRemoteVersionPolicy } from './version-check.js';
import { isVersionAtLeast } from './semver.js';
import { ensureConnectCdpReady, isBridgeRunning, startBridge, stopBridgeProcess, } from './launch.js';
const DEFAULT_IDLE_MS = 5 * 60 * 1000;
const DEFAULT_CHECK_MS = 60 * 1000;
function parsePositiveInt(raw, fallback) {
    const n = Number.parseInt(raw ?? '', 10);
    return Number.isFinite(n) && n > 0 ? n : fallback;
}
export function idleUpdateMs() {
    return parsePositiveInt(process.env.CURSORCONNECT_IDLE_UPDATE_MS, DEFAULT_IDLE_MS);
}
export function idleUpdateCheckMs() {
    return parsePositiveInt(process.env.CURSORCONNECT_IDLE_UPDATE_CHECK_MS, DEFAULT_CHECK_MS);
}
export async function fetchBridgeActivity(idleMs) {
    try {
        const res = await fetch(`http://127.0.0.1:3847/health?idleMs=${encodeURIComponent(String(idleMs))}`, { signal: AbortSignal.timeout(4_000) });
        if (!res.ok)
            return null;
        return (await res.json());
    }
    catch {
        return null;
    }
}
/**
 * When global CLI is behind relay latest and bridge has been idle ≥ idleMs, npm i -g + re-exec supervisor.
 */
export async function maybeIdleAutoUpdate(relayUrl, argv, bridgeEnv) {
    if (!canAutoUpdateCli(argv) || !isBridgeRunning())
        return;
    const policy = await fetchRemoteVersionPolicy(relayUrl);
    if (!policy?.latestCliVersion)
        return;
    if (isVersionAtLeast(CLI_VERSION, policy.latestCliVersion))
        return;
    const idleMs = idleUpdateMs();
    const health = await fetchBridgeActivity(idleMs);
    if (!health?.activity?.idleForUpdate)
        return;
    console.log(t('version.idleAutoUpdating', {
        current: CLI_VERSION,
        latest: policy.latestCliVersion,
        idleMin: String(Math.round(idleMs / 60_000)),
    }));
    stopBridgeProcess();
    if (!installLatestGlobal()) {
        console.warn(t('version.autoUpdateFailed'));
        try {
            const cdpUrl = bridgeEnv.CDP_URL ?? 'http://127.0.0.1:9222';
            await ensureConnectCdpReady({
                cdpUrl,
                noRestartCursor: false,
                syncBridge: async () => {
                    startBridge(bridgeEnv);
                },
                waitBridgeMs: 25_000,
            });
        }
        catch {
            /* supervisor loop will restart bridge */
        }
        return;
    }
    await reexecCursorconnect('_supervisor', argv);
}
