#!/usr/bin/env node
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

console.log('🦾 Building ARM64 binary via WSL...');

// Get the WSL path
const windowsPath = __dirname.replace(/\\/g, '/');
const driveLetter = windowsPath.charAt(0).toLowerCase();
const pathWithoutDrive = windowsPath.substring(2);
const wslPath = `/mnt/${driveLetter}${pathWithoutDrive}`;

console.log(`📍 WSL path: ${wslPath}`);

// Check for Rust in WSL
console.log('🔍 Checking for Rust/Cargo in WSL...');
try {
    execSync('wsl bash -c "command -v cargo"', { stdio: 'pipe' });
    console.log('✅ Rust/Cargo found');
} catch {
    console.log('⚠️  Rust/Cargo not found in WSL, installing...');
    execSync('wsl bash -c "curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y"', { stdio: 'inherit' });
    console.log('✅ Rust installed successfully');
}

// Check for ARM64 target
console.log('🔍 Checking for ARM64 cross-compilation target...');
try {
    const targets = execSync('wsl bash -c ". $HOME/.cargo/env && rustup target list --installed"', { encoding: 'utf8' });
    if (!targets.includes('aarch64-unknown-linux-gnu')) {
        console.log('📦 Adding ARM64 target...');
        execSync('wsl bash -c ". $HOME/.cargo/env && rustup target add aarch64-unknown-linux-gnu"', { stdio: 'inherit' });
        console.log('✅ ARM64 target added');
    } else {
        console.log('✅ ARM64 target already installed');
    }
} catch (error) {
    console.log('📦 Adding ARM64 target...');
    execSync('wsl bash -c ". $HOME/.cargo/env && rustup target add aarch64-unknown-linux-gnu"', { stdio: 'inherit' });
    console.log('✅ ARM64 target added');
}

// Check for ARM64 cross-compiler
console.log('🔍 Checking for ARM64 cross-compiler...');
try {
    execSync('wsl bash -c "command -v aarch64-linux-gnu-gcc"', { stdio: 'pipe' });
    console.log('✅ ARM64 cross-compiler found');
} catch {
    console.log('📦 Installing ARM64 cross-compiler...');
    execSync('wsl bash -c "sudo apt-get update && sudo apt-get install -y gcc-aarch64-linux-gnu"', { stdio: 'inherit' });
    console.log('✅ ARM64 cross-compiler installed');
}

// Check for build dependencies
console.log('🔍 Checking for build dependencies in WSL...');
try {
    execSync('wsl bash -c "pkg-config --exists gtk+-3.0 webkit2gtk-4.1"', { stdio: 'pipe' });
    console.log('✅ Build dependencies found');
} catch {
    console.log('⚠️  Build dependencies not found, installing...');
    execSync('wsl 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');
}

// Build for ARM64
console.log('\n📦 Building ARM64 binary...');
const buildCmd = `wsl bash -c "cd ${wslPath} && . $HOME/.cargo/env && export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc && PKG_CONFIG_ALLOW_CROSS=1 cargo build --release --target aarch64-unknown-linux-gnu"`;
execSync(buildCmd, { stdio: 'inherit' });
console.log('✅ ARM64 build completed');

// Copy the binary
const sourcePath = path.join(__dirname, 'target', 'aarch64-unknown-linux-gnu', 'release', 'msgernative');
const destDir = path.join(__dirname, 'bin');
const destPath = path.join(destDir, 'msgernative-arm64');

if (!fs.existsSync(destDir)) {
    fs.mkdirSync(destDir, { recursive: true });
}

fs.copyFileSync(sourcePath, destPath);
console.log(`✅ Binary copied to: ${destPath}`);

const stats = fs.statSync(destPath);
const sizeMB = (stats.size / (1024 * 1024)).toFixed(2);
console.log(`📊 Binary size: ${sizeMB} MB`);

console.log('\n🎉 ARM64 build process completed!');
