#!/usr/bin/env node

import { execSync } from 'child_process';
import { resolve } from 'path';

// Get the absolute path to msger-native directory
const msgerNativePath = resolve(import.meta.dirname);

// Convert Windows path to WSL path
// Example: Y:\dev\utils\msger\msger-native -> /mnt/y/dev/utils/msger/msger-native
function toWSLPath(winPath: string): string {
    // Replace backslashes with forward slashes
    let path = winPath.replace(/\\/g, '/');
    
    // Convert drive letter (e.g., Y: -> /mnt/y)
    path = path.replace(/^([A-Za-z]):/, (_, drive) => `/mnt/${drive.toLowerCase()}`);
    
    return path;
}

const wslPath = toWSLPath(msgerNativePath);

console.log('🐧 Building Linux binary via WSL...');
console.log(`📍 WSL path: ${wslPath}`);

// Check if Rust/Cargo is installed in WSL, and install if not
console.log('🔍 Checking for Rust/Cargo in WSL...');
try {
    execSync('wsl -e bash -c "command -v cargo"', { stdio: 'pipe' });
    console.log('✅ Rust/Cargo found');
} catch {
    console.log('⚠️  Rust/Cargo not found in WSL, installing...');
    try {
        execSync(
            'wsl -e bash -c "curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && source ~/.cargo/env"',
            { stdio: 'inherit' }
        );
        console.log('✅ Rust installed successfully');
    } catch (error: any) {
        console.error('❌ Failed to install Rust:', error.message);
        console.error('Please install Rust manually in WSL:');
        console.error('  wsl');
        console.error('  curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh');
        process.exit(1);
    }
}

// Check if pkg-config and GTK dependencies are installed
console.log('🔍 Checking for build dependencies in WSL...');
try {
    execSync('wsl -e bash -c "command -v pkg-config"', { stdio: 'pipe' });
    console.log('✅ Build dependencies found');
} catch {
    console.log('⚠️  Build dependencies not found, installing...');
    console.log('   Installing: pkg-config, libgtk-3-dev, libwebkit2gtk-4.1-dev, libsoup-3.0-dev');
    try {
        execSync(
            'wsl -e bash -c "sudo apt-get update && sudo apt-get install -y pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev libsoup-3.0-dev"',
            { stdio: 'inherit' }
        );
        console.log('✅ Build dependencies installed successfully');
    } catch (error: any) {
        console.error('❌ Failed to install build dependencies:', error.message);
        console.error('Please install manually in WSL:');
        console.error('  wsl');
        console.error('  sudo apt-get update');
        console.error('  sudo apt-get install -y pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev libsoup-3.0-dev');
        process.exit(1);
    }
}

try {
    execSync(`wsl -e bash -c "source ~/.cargo/env 2>/dev/null || true && cd '${wslPath}' && npm run build"`, { 
        stdio: 'inherit' 
    });
    console.log('✅ WSL build completed');
} catch (error: any) {
    console.error('❌ WSL build failed:', error.message);
    process.exit(1);
}
