/**
 * Ensure vendored Gateway has node_modules + generated Prisma client.
 * prepublishOnly prunes apps/gateway/node_modules; postinstall restores for consumers,
 * but linked/global installs from a dev tree need this at boot too.
 */
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
function shell() {
    return process.platform === 'win32' ? process.env['COMSPEC'] || 'cmd.exe' : undefined;
}
function gatewayPrismaClientPath(packageRoot) {
    return path.join(packageRoot, 'apps', 'gateway', 'node_modules', '.prisma', 'client');
}
function gatewayDistPath(packageRoot) {
    return path.join(packageRoot, 'apps', 'gateway', 'dist', 'index.js');
}
export function isGatewayPrismaReady(packageRoot) {
    return fs.existsSync(gatewayDistPath(packageRoot)) && fs.existsSync(gatewayPrismaClientPath(packageRoot));
}
/**
 * npm install (if needed) + prisma generate for the vendored Gateway bundle.
 */
export function ensureGatewayPrismaReady(packageRoot) {
    if (isGatewayPrismaReady(packageRoot)) {
        return true;
    }
    const gatewayDir = path.join(packageRoot, 'apps', 'gateway');
    const packageJson = path.join(gatewayDir, 'package.json');
    const schema = path.join(packageRoot, 'prisma', 'schema.prisma');
    if (!fs.existsSync(packageJson) || !fs.existsSync(schema)) {
        return false;
    }
    const sh = shell();
    const execOpts = {
        stdio: 'pipe',
        windowsHide: true,
        ...(sh ? { shell: sh } : {}),
    };
    const nodeModules = path.join(gatewayDir, 'node_modules');
    if (!fs.existsSync(nodeModules) || fs.readdirSync(nodeModules).length === 0) {
        try {
            execSync('npm install --omit=dev --no-audit --no-fund --loglevel=error', {
                ...execOpts,
                cwd: gatewayDir,
                timeout: 180000,
            });
        }
        catch {
            return false;
        }
    }
    try {
        execSync('npm run db:generate', {
            ...execOpts,
            cwd: gatewayDir,
            timeout: 120000,
        });
    }
    catch {
        return false;
    }
    return isGatewayPrismaReady(packageRoot);
}
//# sourceMappingURL=gateway-prisma-bootstrap.js.map