#!/usr/bin/env node
import { join, resolve } from 'path';
import { buildPairUri, ensurePairingIdentity, loadPairingIdentity, refreshPairingCode, } from './pairing-identity.js';
import { ensureConnectCdpReady, isBridgeRunning, startBridge, startSupervisor, stopBridgeProcess, stopConnect, } 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 { uninstallLegacyAutostart } from './legacy-autostart.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) {
    uninstallLegacyAutostart();
    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 });
    const syncBridge = async () => {
        if (isBridgeRunning()) {
            console.error(t('start.restartingBridge'));
            stopBridgeProcess();
        }
        startBridge(env);
    };
    const cdpOk = await ensureConnectCdpReady({
        cdpUrl: env.CDP_URL,
        restartCursor,
        noRestartCursor,
        syncBridge,
        waitBridgeMs: 35_000,
    });
    if (!cdpOk) {
        console.error('');
        console.error(t('start.cdpRequired'));
        console.error(t('start.cdpThenRetry'));
        console.error('  cursorconnect start');
        console.error('');
        process.exit(1);
    }
    let readiness = await awaitStartupReadiness(relayUrl, refreshed, {
        waitMs: 45_000,
        requireCdp: true,
    });
    if (!readiness.ready && !readiness.localCdp) {
        const recovered = await ensureConnectCdpReady({
            cdpUrl: env.CDP_URL,
            restartCursor: true,
            noRestartCursor: false,
            syncBridge,
            waitBridgeMs: 35_000,
        });
        if (recovered) {
            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);
    startSupervisor(env, serviceArgv(argv));
    console.log('');
    console.log(`  ${t('start.cdpSupervisorHint')}`);
}
async function cmdStop() {
    stopConnect();
    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);
}
/** Привязка без POST /api/pair (когда iPhone не достучится до relay HTTP). */
function cmdPairLink() {
    const identity = loadPairingIdentity();
    if (!identity) {
        console.error(t('pairLink.noIdentity'));
        process.exit(1);
    }
    const { relayUrl } = resolveRelayConfig([USER_CONFIG_ENV]);
    const base = (relayUrl || DEFAULT_RELAY_URL).replace(/\/$/, '');
    const uri = buildPairUri(base, identity);
    console.log('');
    console.log(t('pairLink.title'));
    console.log('');
    console.log(uri);
    console.log('');
    console.log(t('pairLink.hint'));
    console.log('');
}
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 cmdLegacyAutostartRemoved() {
    uninstallLegacyAutostart();
    console.log(t('autostart.removed'));
}
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 '_supervisor':
        case 'run-service':
            if (cmd === 'run-service') {
                console.warn(t('autostart.runServiceDeprecated'));
                uninstallLegacyAutostart();
            }
            await import('./cdp-supervisor.js');
            break;
        case 'install-autostart':
        case 'uninstall-autostart':
            await cmdLegacyAutostartRemoved();
            break;
        case 'update':
            await cmdUpdateGlobal();
            break;
        case 'pair-link':
            cmdPairLink();
            break;
        default:
            console.log(t('usage.body'));
            process.exit(cmd === 'help' ? 0 : 1);
    }
}
main().catch((e) => {
    console.error(e);
    process.exit(1);
});
