import { existsSync, readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
const MIN_FALLBACK = '0.1.7';
function readJsonVersion(path) {
    if (!existsSync(path))
        return null;
    try {
        const raw = JSON.parse(readFileSync(path, 'utf-8'));
        const v = raw.cliVersion?.trim() || raw.version?.trim();
        return v || null;
    }
    catch {
        return null;
    }
}
/** Версия для relay auth (должна быть ≥ MIN_CLI_VERSION на VPS). */
export function connectorClientVersion() {
    const fromEnv = process.env.CURSORCONNECT_CLI_VERSION?.trim();
    if (fromEnv && fromEnv !== '0.0.0')
        return fromEnv;
    const bridgeRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
    const fromBundle = readJsonVersion(join(bridgeRoot, 'connector-version.json'));
    if (fromBundle)
        return fromBundle;
    const candidates = [
        join(bridgeRoot, '..', 'connect', 'package.json'),
        join(bridgeRoot, 'package.json'),
    ];
    for (const p of candidates) {
        if (!existsSync(p))
            continue;
        try {
            const pkg = JSON.parse(readFileSync(p, 'utf-8'));
            if (pkg.version?.trim())
                return pkg.version.trim();
        }
        catch {
            /* next */
        }
    }
    return MIN_FALLBACK;
}
