/**
 * Boot sequence - ensures clean system state before launching 4r
 * Handles stale processes, in-progress updates, and broken installs
 */
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { forceClearGlobalDeferredNpmLock } from './deferred-npm-install-lock.js';
/**
 * Kill any stale 4r/Gateway processes that might lock files
 */
export function killStaleProcesses() {
    if (process.platform !== 'win32') {
        // POSIX: killall is less aggressive than pkill -9
        try {
            execSync('pkill -f "4runr-os|mk3-tui" || true', { stdio: 'ignore' });
        }
        catch {
            // ignore
        }
        return;
    }
    // Windows: Use PowerShell Get-Process (wmic was removed in Windows 11+)
    try {
        const ps = `Get-Process node -ErrorAction SilentlyContinue | Where-Object { $_.Path -like '*4runr-os*' -or $_.CommandLine -like '*gateway*' } | ForEach-Object { Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue }`;
        execSync(`powershell -NoProfile -Command "${ps}"`, {
            stdio: 'ignore',
            timeout: 10000,
            windowsHide: true,
        });
    }
    catch {
        // Fallback: just kill all node except current process
        try {
            execSync(`taskkill /F /IM node.exe /FI "PID ne ${process.pid}"`, {
                stdio: 'ignore',
                windowsHide: true,
            });
        }
        catch {
            // ignore
        }
    }
}
/**
 * Check if Prisma client is properly generated
 */
function checkPrismaClient() {
    try {
        const globalRoot = execSync('npm root -g', { encoding: 'utf-8' }).trim();
        const prismaPath = path.join(globalRoot, '4runr-os', 'apps', 'gateway', 'node_modules', '.prisma', 'client');
        return fs.existsSync(prismaPath);
    }
    catch {
        return false;
    }
}
/**
 * Check if Gateway bundle is intact
 */
function checkGatewayBundle() {
    try {
        const globalRoot = execSync('npm root -g', { encoding: 'utf-8' }).trim();
        const gatewayDist = path.join(globalRoot, '4runr-os', 'apps', 'gateway', 'dist', 'index.js');
        return fs.existsSync(gatewayDist);
    }
    catch {
        return false;
    }
}
/**
 * Repair broken install by regenerating Prisma
 */
async function repairInstall() {
    try {
        const globalRoot = execSync('npm root -g', { encoding: 'utf-8' }).trim();
        const gatewayDir = path.join(globalRoot, '4runr-os', 'apps', 'gateway');
        if (!fs.existsSync(gatewayDir)) {
            return false;
        }
        process.stderr.write('🔧 Repairing installation...\n');
        // Run npm install + prisma generate in gateway
        execSync('npm install --no-audit', {
            cwd: gatewayDir,
            stdio: 'pipe',
            windowsHide: true,
        });
        execSync('npm run db:generate', {
            cwd: gatewayDir,
            stdio: 'pipe',
            windowsHide: true,
        });
        process.stderr.write('✓ Repair complete\n');
        return true;
    }
    catch (err) {
        process.stderr.write(`⚠️  Repair failed: ${err instanceof Error ? err.message : String(err)}\n`);
        return false;
    }
}
/**
 * Perform full boot sequence health check
 */
export async function performBootSequence() {
    const warnings = [];
    // Clear stale npm-update lock so manual `npm install -g` never stays blocked forever
    forceClearGlobalDeferredNpmLock();
    // Step 1: Kill stale processes
    try {
        killStaleProcesses();
        await new Promise(r => setTimeout(r, 500));
    }
    catch (err) {
        warnings.push(`Could not kill stale processes: ${err instanceof Error ? err.message : String(err)}`);
    }
    // Step 2: Lock already cleared above (legacy waits removed — they blocked recovery)
    // Step 3: Health checks
    const prismaOk = checkPrismaClient();
    const gatewayOk = checkGatewayBundle();
    if (!prismaOk || !gatewayOk) {
        warnings.push('Installation health check failed');
        // Attempt repair
        const repaired = await repairInstall();
        if (!repaired) {
            return {
                ok: false,
                error: 'Installation is broken and auto-repair failed. Run: npm install -g 4runr-os@latest',
                warnings,
            };
        }
    }
    return { ok: true, warnings: warnings.length > 0 ? warnings : undefined };
}
//# sourceMappingURL=boot-sequence.js.map