/**
 * System verification - ensures everything is ready to run
 * Auto-detects and fixes issues before launching
 */
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { getMk3UserCachePath } from './mk3-binary-bootstrap.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const platform = process.platform;
const isWindows = platform === 'win32';
/**
 * Verify system is ready and auto-fix issues
 */
export async function verifySystem() {
    // Check if binary exists
    const binaryName = isWindows ? 'mk3-tui.exe' : 'mk3-tui';
    const possiblePaths = [
        path.join(__dirname, '..', 'mk3-tui', 'binaries', `${platform}-${process.arch}`, binaryName),
        path.join(__dirname, '..', 'mk3-tui', 'binaries', platform, binaryName),
        path.join(__dirname, '..', 'mk3-tui', 'target', 'release', binaryName),
        getMk3UserCachePath(binaryName),
        path.join(__dirname, '..', '..', '..', 'apps', 'mk3-tui', 'target', 'release', binaryName),
    ];
    // Check if binary exists
    for (const testPath of possiblePaths) {
        if (fs.existsSync(testPath)) {
            return true; // Binary found, ready to go!
        }
    }
    // Binary not found - verify system is ready (but don't build here)
    // Building will happen in index.ts if needed
    process.stderr.write('\n🔍 Verifying system...\n');
    // Check Rust
    let rustInstalled = false;
    try {
        execSync('cargo --version', { stdio: 'ignore' });
        rustInstalled = true;
    }
    catch {
        process.stderr.write('❌ Rust not installed.\n');
        process.stderr.write('   Run setup first: 4runr-setup\n');
        process.stderr.write('   Or install Rust: https://rustup.rs/\n\n');
        return false;
    }
    // On Windows, check/fix MSVC linker issue
    if (isWindows) {
        let msvcAvailable = false;
        try {
            execSync('where link.exe', { stdio: 'ignore' });
            msvcAvailable = true;
        }
        catch {
            // MSVC not available - check if MinGW is available for GNU toolchain
            let mingwAvailable = false;
            let mingwPath = '';
            try {
                const dlltoolPath = execSync('where dlltool.exe', { encoding: 'utf-8', stdio: 'pipe' }).trim();
                mingwAvailable = true;
                mingwPath = path.dirname(dlltoolPath);
            }
            catch {
                // Check common MinGW locations
                const commonPaths = [
                    'C:\\mingw64\\bin',
                    'C:\\msys64\\mingw64\\bin',
                    path.join(process.env.ProgramFiles || 'C:\\Program Files', 'mingw-w64'),
                ];
                for (const testPath of commonPaths) {
                    const dlltoolPath = path.join(testPath, 'dlltool.exe');
                    if (fs.existsSync(dlltoolPath)) {
                        mingwAvailable = true;
                        mingwPath = path.dirname(dlltoolPath);
                        process.env.PATH = `${mingwPath};${process.env.PATH}`;
                        break;
                    }
                }
            }
            if (!mingwAvailable) {
                process.stderr.write('❌ MinGW not found (required for GNU toolchain).\n');
                process.stderr.write('   Run setup to install: 4runr-setup\n');
                process.stderr.write('   Or install manually: winget install mingw-w64.mingw-w64\n');
                process.stderr.write('   Then restart terminal and run 4r again\n\n');
                return false;
            }
            // Ensure MinGW is in PATH
            if (mingwPath && process.env.PATH && !process.env.PATH.includes(mingwPath)) {
                process.env.PATH = `${mingwPath};${process.env.PATH}`;
            }
            else if (mingwPath && !process.env.PATH) {
                process.env.PATH = mingwPath;
            }
            if (mingwAvailable) {
                process.stderr.write('⚠️  MSVC linker not found. Using GNU toolchain...\n');
                try {
                    // Check if GNU toolchain is installed
                    execSync('rustup toolchain list', { encoding: 'utf-8', stdio: 'pipe' });
                    // Try to install and use GNU toolchain
                    try {
                        execSync('rustup toolchain install stable-x86_64-pc-windows-gnu', { stdio: 'pipe' });
                    }
                    catch {
                        // Already installed or failed
                    }
                    try {
                        execSync('rustup default stable-x86_64-pc-windows-gnu', { stdio: 'pipe' });
                        process.stderr.write('✅ Using GNU toolchain\n');
                    }
                    catch {
                        // Failed to switch
                    }
                }
                catch {
                    // Can't fix automatically
                }
            }
        }
    }
    // Verify source exists (but don't build - that happens in index.ts)
    const mk3Path = path.join(__dirname, '..', 'mk3-tui');
    if (!fs.existsSync(mk3Path)) {
        process.stderr.write('❌ Source not found in package.\n');
        process.stderr.write('   Please reinstall: npm install -g 4runr-os@latest\n\n');
        return false;
    }
    // System is ready (Rust installed, source exists, toolchain configured)
    // Binary will be built by index.ts if needed
    return true;
}
//# sourceMappingURL=system-verify.js.map