import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { homedir } from 'os';
import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
const CONFIG_DIR = join(homedir(), '.cursorconnect');
const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
export function loadInstallConfig() {
    if (!existsSync(CONFIG_FILE))
        return null;
    try {
        const data = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'));
        if (!data.repoRoot || !isValidRepoRoot(data.repoRoot))
            return null;
        return { repoRoot: resolve(data.repoRoot) };
    }
    catch {
        return null;
    }
}
export function saveInstallConfig(repoRoot) {
    const abs = resolve(repoRoot);
    if (!isValidRepoRoot(abs)) {
        throw new Error(`Не найден Cursor Connect (bridge) в ${abs} (ожидается …/bridge/package.json)`);
    }
    mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
    writeFileSync(CONFIG_FILE, JSON.stringify({ repoRoot: abs }, null, 2), { mode: 0o600 });
}
export function isValidRepoRoot(dir) {
    return existsSync(join(dir, 'bridge', 'package.json'));
}
/** Monorepo dev: connect package inside repo */
function devRepoRoot() {
    const here = dirname(fileURLToPath(import.meta.url));
    const candidate = resolve(here, '..', '..');
    return isValidRepoRoot(candidate) ? candidate : null;
}
function findRepoFromCwd() {
    let dir = process.cwd();
    for (let i = 0; i < 12; i++) {
        if (isValidRepoRoot(dir))
            return resolve(dir);
        const parent = dirname(dir);
        if (parent === dir)
            break;
        dir = parent;
    }
    return null;
}
export function resolveRepoRoot() {
    const fromEnv = process.env.CURSORCONNECT_ROOT?.trim();
    if (fromEnv && isValidRepoRoot(fromEnv))
        return resolve(fromEnv);
    const fromConfig = loadInstallConfig();
    if (fromConfig)
        return fromConfig.repoRoot;
    const fromCwd = findRepoFromCwd();
    if (fromCwd)
        return fromCwd;
    const fromDev = devRepoRoot();
    if (fromDev)
        return fromDev;
    throw new Error('Не найден Cursor Connect (bridge).\n' +
        '  npm install -g cursorconnect && cursorconnect start');
}
export function configFilePath() {
    return CONFIG_FILE;
}
