#!/usr/bin/env node
/**
 * Pi Diagnostics Script
 * Runs on the Pi to check build requirements
 */

import { execSync } from 'child_process';
import fs from 'fs';

const COLORS = {
    reset: '\x1b[0m',
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m',
    white: '\x1b[37m',
    bgRed: '\x1b[41m',
    bgGreen: '\x1b[42m',
};

function log(message: string, color = COLORS.reset) {
    console.log(`${color}${message}${COLORS.reset}`);
}

function exec(cmd: string): string {
    try {
        return execSync(cmd, { encoding: 'utf8' });
    } catch {
        return '';
    }
}

function checkCommand(cmd: string, name: string): boolean {
    const result = exec(`command -v ${cmd}`).trim();
    if (result) {
        log(`✅ ${name} found: ${result}`, COLORS.green);
        return true;
    } else {
        log(`❌ ${name} NOT found`, COLORS.red);
        return false;
    }
}

function checkPkgConfig(pkg: string, minVersion?: string): { found: boolean; version: string } {
    const version = exec(`pkg-config --modversion ${pkg} 2>/dev/null`).trim();
    if (!version) {
        log(`❌ ${pkg} NOT found via pkg-config`, COLORS.red);
        return { found: false, version: '' };
    }

    if (minVersion) {
        const versionParts = version.split('.').map(Number);
        const minParts = minVersion.split('.').map(Number);
        const isOldEnough = versionParts[0] > minParts[0] ||
            (versionParts[0] === minParts[0] && versionParts[1] >= minParts[1]);

        if (isOldEnough) {
            log(`✅ ${pkg} version ${version} (>= ${minVersion})`, COLORS.green);
            return { found: true, version };
        } else {
            log(`⚠️  ${pkg} version ${version} (need >= ${minVersion})`, COLORS.yellow);
            return { found: true, version };
        }
    } else {
        log(`✅ ${pkg} version ${version}`, COLORS.green);
        return { found: true, version };
    }
}

log('\n🔍 Raspberry Pi Build Requirements Diagnostic\n', COLORS.cyan);

// Check OS
log('📋 OS Information:', COLORS.blue);
const osRelease = exec('cat /etc/os-release');
const osName = osRelease.match(/PRETTY_NAME="([^"]+)"/)?.[1] || 'Unknown';
const osVersion = osRelease.match(/VERSION_ID="([^"]+)"/)?.[1] || 'Unknown';
log(`   ${osName}`, COLORS.white);

// Check architecture
const arch = exec('uname -m').trim();
log(`   Architecture: ${arch}\n`, COLORS.white);

// Check build tools
log('🔧 Build Tools:', COLORS.blue);
const hasGcc = checkCommand('gcc', 'C Compiler (gcc)');
const hasMake = checkCommand('make', 'Make');
const hasCargo = checkCommand('cargo', 'Rust/Cargo');
const hasPkgConfig = checkCommand('pkg-config', 'pkg-config');

// Check libraries
log('\n📚 Required Libraries:', COLORS.blue);
const glib = checkPkgConfig('glib-2.0', '2.70');
const gobject = checkPkgConfig('gobject-2.0', '2.70');
const gio = checkPkgConfig('gio-2.0', '2.70');
const gtk = checkPkgConfig('gtk+-3.0');
const webkit4_1 = checkPkgConfig('webkit2gtk-4.1');
const webkit4_0 = checkPkgConfig('webkit2gtk-4.0');

// Summary
log('\n📊 Summary:', COLORS.blue);

const allToolsReady = hasGcc && hasMake && hasCargo && hasPkgConfig;
const glibOk = glib.found && parseFloat(glib.version) >= 2.70;
const allLibsReady = glib.found && gobject.found && gio.found && gtk.found && (webkit4_1.found || webkit4_0.found);

if (allToolsReady && glibOk && allLibsReady) {
    log('✅ All requirements met! Ready to build.', COLORS.green);
} else {
    log('❌ Some requirements missing or outdated', COLORS.red);

    if (!glibOk && glib.found) {
        log('\n⚠️  CRITICAL ISSUE:', COLORS.bgRed + COLORS.white);
        log(`   GLib version ${glib.version} is too old (need >= 2.70)`, COLORS.yellow);
        log(`   Your OS: ${osName}`, COLORS.white);
        log(`\n   Solutions:`, COLORS.cyan);
        log(`   1. Upgrade to Debian 12 (Bookworm) or later:`, COLORS.white);
        log(`      sudo apt update && sudo apt full-upgrade`, COLORS.white);
        log(`   2. Or use wry 0.24 which supports glib 2.56+`, COLORS.white);
    }

    if (!allToolsReady) {
        log('\n💡 Missing tools - install with:', COLORS.cyan);
        if (!hasGcc || !hasMake) log('   sudo apt install build-essential', COLORS.white);
        if (!hasCargo) log('   curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh', COLORS.white);
        if (!hasPkgConfig) log('   sudo apt install pkg-config', COLORS.white);
    }

    if (!allLibsReady) {
        log('\n💡 Missing libraries - install with:', COLORS.cyan);
        log('   sudo apt install libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.1-dev', COLORS.white);
        log('   OR (if 4.1 unavailable):', COLORS.white);
        log('   sudo apt install libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.0-dev', COLORS.white);
    }
}

log('', COLORS.reset);
