import { ensurePairingIdentity, refreshPairingCode, } from './pairing-identity.js';
import { ensureCursorCdp, isBridgeRunning, startBridge, } from './launch.js';
import { BRIDGE_LOG_FILE } from './paths.js';
import { t } from './i18n.js';
import { idleUpdateCheckMs, maybeIdleAutoUpdate, } from './idle-auto-update.js';
const WATCH_MS = 8_000;
function sleep(ms) {
    return new Promise((r) => setTimeout(r, ms));
}
/** Держит Cursor Connect в фоне (для launchd KeepAlive). */
export async function runServiceLoop(bridgeEnv, serviceArgv = []) {
    const identity = ensurePairingIdentity();
    refreshPairingCode(identity);
    const boot = async () => {
        if (isBridgeRunning())
            return;
        const cdpUrl = bridgeEnv.CDP_URL ?? 'http://127.0.0.1:9222';
        const cdpOk = await ensureCursorCdp({ cdpUrl, noRestartCursor: false });
        if (!cdpOk) {
            console.error(t('service.cdpUnavailable'));
            return;
        }
        try {
            startBridge(bridgeEnv);
            console.log(t('service.bridgeStarted', { log: BRIDGE_LOG_FILE }));
        }
        catch (e) {
            console.error(t('service.startFailed'), e);
        }
    };
    await boot();
    const relayUrl = (bridgeEnv.RELAY_URL ?? '').replace(/\/$/, '');
    let lastIdleUpdateCheck = Date.now();
    for (;;) {
        await sleep(WATCH_MS);
        if (!isBridgeRunning()) {
            console.error(t('service.exitedRestarting'));
            await boot();
        }
        if (relayUrl && Date.now() - lastIdleUpdateCheck >= idleUpdateCheckMs()) {
            lastIdleUpdateCheck = Date.now();
            await maybeIdleAutoUpdate(relayUrl, serviceArgv, bridgeEnv);
        }
    }
}
