import { copyFileSync, existsSync, mkdirSync } from 'fs';
import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
import { CURSORCONNECT_DIR } from './paths.js';
import { loadInstallConfig } from './repo-root.js';
export const USER_CONFIG_ENV = join(CURSORCONNECT_DIR, 'config.env');
export function resolvePackageRoot() {
    return resolve(dirname(fileURLToPath(import.meta.url)), '..');
}
export function isValidBridgeDir(dir) {
    return existsSync(join(dir, 'dist', 'index.js'));
}
function bundledBridgeDir() {
    const dir = join(resolvePackageRoot(), 'bridge-runtime');
    return isValidBridgeDir(dir) ? dir : null;
}
function devMonorepoBridge() {
    const candidate = join(resolvePackageRoot(), '..', 'bridge');
    return isValidBridgeDir(candidate) ? resolve(candidate) : null;
}
function findBridgeFromCwd() {
    let dir = process.cwd();
    for (let i = 0; i < 12; i++) {
        const bridge = join(dir, 'bridge');
        if (isValidBridgeDir(bridge))
            return resolve(bridge);
        const parent = dirname(dir);
        if (parent === dir)
            break;
        dir = parent;
    }
    return null;
}
/** Каталог bridge для spawn (bundled npm, monorepo dev или legacy init). */
export function resolveBridgeDir() {
    const fromEnv = process.env.CURSORCONNECT_BRIDGE_DIR?.trim();
    if (fromEnv && isValidBridgeDir(fromEnv))
        return resolve(fromEnv);
    const fromCwd = findBridgeFromCwd();
    if (fromCwd)
        return fromCwd;
    const fromDev = devMonorepoBridge();
    if (fromDev)
        return fromDev;
    const bundled = bundledBridgeDir();
    if (bundled)
        return bundled;
    const legacy = loadInstallConfig();
    if (legacy) {
        const bridge = join(legacy.repoRoot, 'bridge');
        if (isValidBridgeDir(bridge))
            return bridge;
    }
    throw new Error('Не найден Cursor Connect (bridge).\n' +
        '  npm install -g cursorconnect && cursorconnect start\n' +
        '  (для разработки: клон репо + npm install в корне)');
}
export function ensureUserConfig() {
    mkdirSync(CURSORCONNECT_DIR, { recursive: true, mode: 0o700 });
    if (existsSync(USER_CONFIG_ENV))
        return;
    const devBridge = findBridgeFromCwd() ?? devMonorepoBridge();
    const devEnv = devBridge ? join(devBridge, '.env') : '';
    if (devEnv && existsSync(devEnv)) {
        copyFileSync(devEnv, USER_CONFIG_ENV);
        return;
    }
    const bundled = join(resolvePackageRoot(), 'config.env.defaults');
    if (existsSync(bundled)) {
        copyFileSync(bundled, USER_CONFIG_ENV);
        return;
    }
    const template = join(resolvePackageRoot(), 'bridge-runtime', '.env.example');
    if (existsSync(template)) {
        copyFileSync(template, USER_CONFIG_ENV);
        return;
    }
    const devTemplate = join(resolvePackageRoot(), '..', 'bridge', '.env.example');
    if (existsSync(devTemplate)) {
        copyFileSync(devTemplate, USER_CONFIG_ENV);
    }
}
