import { execSync } from 'child_process';
import { t } from './i18n.js';
import { existsSync, readdirSync, statSync } from 'fs';
import { join } from 'path';
function newestMtimeMs(dir) {
    let max = 0;
    for (const name of readdirSync(dir, { withFileTypes: true })) {
        const path = join(dir, name.name);
        if (name.isDirectory()) {
            max = Math.max(max, newestMtimeMs(path));
            continue;
        }
        if (!name.isFile())
            continue;
        if (!/\.(ts|tsx|json)$/.test(name.name))
            continue;
        max = Math.max(max, statSync(path).mtimeMs);
    }
    return max;
}
export function isBridgeSrcNewerThanDist(bridgeDir) {
    const dist = join(bridgeDir, 'dist', 'index.js');
    const src = join(bridgeDir, 'src');
    if (!existsSync(src))
        return false;
    if (!existsSync(dist))
        return true;
    return newestMtimeMs(src) > statSync(dist).mtimeMs;
}
export function buildBridge(bridgeDir) {
    const monorepoRoot = join(bridgeDir, '..');
    const hasWorkspace = existsSync(join(monorepoRoot, 'package.json')) &&
        existsSync(join(monorepoRoot, 'bridge', 'package.json'));
    if (hasWorkspace) {
        execSync('npm run build -w bridge', {
            cwd: monorepoRoot,
            stdio: 'inherit',
        });
        return;
    }
    execSync('npm run build', { cwd: bridgeDir, stdio: 'inherit' });
}
/** Dev: compile bridge when `src/` is newer than `dist/` (runtime = dist, not ts). */
export function ensureBridgeBuilt(bridgeDir) {
    if (process.env.CURSORCONNECT_SKIP_BRIDGE_BUILD === '1')
        return;
    if (!isBridgeSrcNewerThanDist(bridgeDir))
        return;
    console.error(t('bridge.rebuilding'));
    buildBridge(bridgeDir);
}
