#!/usr/bin/env node
import { join, resolve } from 'path';
import { ensurePairingIdentity, loadPairingIdentity, refreshPairingCode, } from './pairing-identity.js';
import { ensureCursorCdp, isBridgeRunning, printManualCdpInstructions, startBridge, stopBridge, } from './launch.js';
import { printPairingToTerminal } from './print-pairing.js';
import { BRIDGE_LOG_FILE } from './paths.js';
import { ensureUserConfig, isValidBridgeDir, resolveBridgeDir, USER_CONFIG_ENV, } from './bridge-dir.js';
import { configFilePath, saveInstallConfig } from './repo-root.js';
import { formatDiagnoseReport, runDiagnose } from './diagnose.js';
import { awaitStartupReadiness, formatStartupChecklist, printStartupFailure, snapshotStartupReadiness, } from './startup-check.js';
import { DEFAULT_RELAY_URL, loadEnvFile, resolveRelayConfig } from './relay-config.js';
import { cmdUpdateGlobal, ensureCliVersionForRelay } from './cli-auto-update.js';
import { assertBundledBridgeSupportsRelay, bundledBridgeHasClientVersion, } from './bundled-bridge-check.js';
import { CLI_VERSION } from './cli-version.js';
import { askYesNo } from './ask.js';
import { installCursorCdpLauncher, installMacAutostart, isAutostartInstalled, uninstallMacAutostart, } from './macos-autostart.js';
import { runServiceLoop } from './run-service.js';
import { t } from './i18n.js';
function bridgeEnv(identity) {
    ensureUserConfig();
    const bridgeDotEnv = join(resolveBridgeDir(), '.env');
    const { relayUrl, relayToken } = resolveRelayConfig([bridgeDotEnv]);
    if (!relayToken) {
        console.error(t('start.relayTokenMissing', { path: USER_CONFIG_ENV }));
        process.exit(1);
    }
    const file = {
        ...loadEnvFile(bridgeDotEnv),
        ...loadEnvFile(USER_CONFIG_ENV),
    };
    return {
        RELAY_URL: relayUrl,
        RELAY_TOKEN: relayToken,
        RELAY_ROOM_ID: identity.roomId,
        SERVER_HOST: '127.0.0.1',
        SERVER_PORT: '3847',
        CDP_URL: file.CDP_URL ?? 'http://127.0.0.1:9222',
        CURSORCONNECT_CLI_VERSION: CLI_VERSION,
    };
}
function startFlags(argv) {
    return {
        restartCursor: argv.includes('--restart-cursor') || argv.includes('-r'),
        noRestartCursor: argv.includes('--no-restart-cursor'),
    };
}
function serviceArgv(argv) {
    return argv.filter((a) => a !== '--no-auto-update');
}
async function cmdStart(argv) {
    assertBundledBridgeSupportsRelay();
    const { restartCursor, noRestartCursor } = startFlags(argv);
    const identity = ensurePairingIdentity();
    const refreshed = refreshPairingCode(identity);
    const env = bridgeEnv(refreshed);
    const relayUrl = env.RELAY_URL;
    await ensureCliVersionForRelay(relayUrl, { subcommand: 'start', argv });
    // 1) Сначала CDP (порт 9222), иначе bridge стартует без сайдбара Cursor.
    const cdpPortOk = await ensureCursorCdp({
        cdpUrl: env.CDP_URL,
        restartCursor,
        noRestartCursor,
    });
    if (!cdpPortOk) {
        console.error('');
        console.error(t('start.cdpRequired'));
        console.error(t('start.cdpThenRetry'));
        console.error('  cursorconnect start');
        console.error('');
        printManualCdpInstructions();
        process.exit(1);
    }
    if (isBridgeRunning()) {
        console.error(t('start.restartingBridge'));
        stopBridge();
    }
    startBridge(env);
    const readiness = await awaitStartupReadiness(relayUrl, refreshed, {
        waitMs: 45_000,
        requireCdp: true,
    });
    if (!readiness.ready) {
        printStartupFailure(readiness, BRIDGE_LOG_FILE);
        process.exit(1);
    }
    console.log('');
    console.log(`  ${t('start.checksBeforePairing')}`);
    for (const line of formatStartupChecklist(readiness)) {
        console.log(`  ${line}`);
    }
    console.log('');
    printPairingToTerminal(refreshed);
    if (process.stdin.isTTY && !isAutostartInstalled()) {
        const yes = await askYesNo(t('start.askAutostart'));
        if (yes) {
            installMacAutostart();
            const cdp = installCursorCdpLauncher();
            console.log('');
            console.log(`  ${t('start.autostartEnabled')}`);
            console.log(`  ${t('start.openCursorFromDock')}`);
            console.log(`  ${cdp}`);
            console.log(`  ${t('start.dockHint')}`);
            console.log(`  ${t('start.pairingCodeViaStatus')}`);
        }
    }
}
async function cmdRunService() {
    assertBundledBridgeSupportsRelay();
    const identity = ensurePairingIdentity();
    refreshPairingCode(identity);
    const env = bridgeEnv(identity);
    await ensureCliVersionForRelay(env.RELAY_URL, {
        subcommand: 'run-service',
        argv: serviceArgv(process.argv.slice(3)),
    });
    console.log(t('service.starting'));
    await runServiceLoop(env, serviceArgv(process.argv.slice(3)));
}
async function cmdInstallAutostart() {
    installMacAutostart();
    const cdp = installCursorCdpLauncher();
    console.log(t('autostart.enabled'));
    console.log(t('autostart.cursorCdpPath', { path: cdp }));
    console.log(t('autostart.codeViaStatus'));
}
async function cmdUninstallAutostart() {
    uninstallMacAutostart();
    console.log(t('autostart.disabled'));
}
async function cmdStop() {
    stopBridge();
    console.log(t('stop.stopped'));
}
async function cmdInit(pathArg) {
    const target = pathArg?.trim() || process.cwd();
    const abs = resolve(target);
    if (!isValidBridgeDir(join(abs, 'bridge'))) {
        console.error(t('init.notRepo', { path: abs }));
        process.exit(1);
    }
    saveInstallConfig(abs);
    console.log(t('init.saved', { path: configFilePath() }));
    console.log(t('init.repoRoot', { path: abs }));
    console.log(`\n${t('init.next')}`);
}
async function cmdDiagnose() {
    const report = await runDiagnose();
    console.log(formatDiagnoseReport(report));
    const failed = report.checks.some((c) => !c.ok);
    process.exit(failed ? 1 : 0);
}
async function cmdStatus() {
    const identity = loadPairingIdentity();
    ensureUserConfig();
    if (!identity) {
        console.error(t('status.noIdentity'));
        process.exit(1);
    }
    console.log(t('status.cliVersion', { version: CLI_VERSION }));
    console.log(bundledBridgeHasClientVersion()
        ? t('status.bundleOk')
        : t('status.bundleStale'));
    console.log(t('status.bridgeProcess', {
        state: isBridgeRunning() ? t('status.bridgeRunning') : t('status.bridgeStopped'),
    }));
    const { relayUrl: relayUrlRaw } = resolveRelayConfig([USER_CONFIG_ENV]);
    const relayUrl = (relayUrlRaw || DEFAULT_RELAY_URL).replace(/\/$/, '');
    const readiness = await snapshotStartupReadiness(relayUrl, identity);
    console.log('');
    console.log(`  ${t('status.stateHeader')}`);
    for (const line of formatStartupChecklist(readiness)) {
        console.log(`  ${line}`);
    }
    if (!readiness.ready) {
        console.log('');
        console.warn(t('status.codeMayFail'));
    }
    console.log('');
    printPairingToTerminal(identity);
}
async function main() {
    const argv = process.argv.slice(2);
    const cmd = argv[0] ?? 'start';
    const rest = argv.slice(1);
    switch (cmd) {
        case 'start':
            await cmdStart(rest);
            break;
        case 'stop':
            await cmdStop();
            break;
        case 'status':
            await cmdStatus();
            break;
        case 'diagnose':
            await cmdDiagnose();
            break;
        case 'init':
            await cmdInit(rest[0]);
            break;
        case 'run-service':
            await cmdRunService();
            break;
        case 'install-autostart':
            await cmdInstallAutostart();
            break;
        case 'uninstall-autostart':
            await cmdUninstallAutostart();
            break;
        case 'update':
            await cmdUpdateGlobal();
            break;
        default:
            console.log(t('usage.body'));
            process.exit(cmd === 'help' ? 0 : 1);
    }
}
main().catch((e) => {
    console.error(e);
    process.exit(1);
});
