const path = require('path');
const fs = require('fs');
const os = require('os');
const { execSync } = require('child_process');

const platform = os.platform();
const arch = os.arch();

// Map Node.js arch to our naming convention
const archMap = {
  'x64': 'x64',
  'ia32': 'x86',
  'arm64': 'arm64',
  'arm': 'arm'
};

const normalizedArch = archMap[arch] || arch;
const platformArch = `${platform}-${normalizedArch}`;

// Check if precompiled binary exists
const prebuildPath = path.join(__dirname, '..', 'prebuilds', platformArch, 'HypertubeNodejsRuntimeAddon.node');
const prebuildExists = fs.existsSync(prebuildPath);

if (prebuildExists) {
  console.log(`✓ Precompiled binary found for ${platformArch}, skipping build.`);
  process.exit(0);
}

// Check if binary already exists in build directory
const buildPath = path.join(__dirname, '..', 'build', 'Release', 'HypertubeNodejsRuntimeAddon.node');
const buildExists = fs.existsSync(buildPath);

if (buildExists) {
  console.log(`✓ Binary already exists in build directory, skipping build.`);
  process.exit(0);
}

// No precompiled binary found, check if node-gyp is available
try {
  execSync('node-gyp --version', { stdio: 'ignore' });
  console.log(`⚠ Precompiled binary not found for ${platformArch}.`);
  console.log(`⚠ Building from source using node-gyp...`);
  console.log(`⚠ This requires node-gyp and build tools to be installed.`);
  console.log(`⚠ For production, use precompiled binaries to avoid this step.`);
  
  // Try to build
  try {
    execSync('node-gyp rebuild', { 
      stdio: 'inherit',
      cwd: path.join(__dirname, '..')
    });
    console.log(`✓ Build completed successfully.`);
  } catch (buildError) {
    console.error(`✗ Build failed. Please ensure node-gyp and build tools are installed.`);
    console.error(`  For Windows: npm install --global windows-build-tools`);
    console.error(`  For Linux: Install build-essential, python, and make`);
    console.error(`  For macOS: Install Xcode Command Line Tools`);
    process.exit(1);
  }
} catch (nodeGypError) {
  console.error(`✗ Precompiled binary not found for ${platformArch} and node-gyp is not available.`);
  console.error(`  Please either:`);
  console.error(`  1. Use a package with precompiled binaries for your platform`);
  console.error(`  2. Install node-gyp: npm install -g node-gyp`);
  console.error(`  3. Install build tools for your platform`);
  process.exit(1);
}

