#!/usr/bin/env node

/**
 * SwarmHack npm Package Build Script
 * Builds binaries for all platforms and packages for npm
 */

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

const VERSION = require('../package.json').version;
const ROOT = path.join(__dirname, '..');
const PROJECT_ROOT = path.join(ROOT, '..', '..');

// Build targets
const TARGETS = [
  { platform: 'linux', arch: 'x64', rust_target: 'x86_64-unknown-linux-gnu' },
  { platform: 'linux', arch: 'arm64', rust_target: 'aarch64-unknown-linux-gnu' },
  { platform: 'darwin', arch: 'x64', rust_target: 'x86_64-apple-darwin' },
  { platform: 'darwin', arch: 'arm64', rust_target: 'aarch64-apple-darwin' },
  { platform: 'win32', arch: 'x64', rust_target: 'x86_64-pc-windows-msvc' },
];

function exec(cmd, options = {}) {
  console.log(`$ ${cmd}`);
  try {
    return execSync(cmd, { stdio: 'inherit', cwd: PROJECT_ROOT, ...options });
  } catch (err) {
    console.error(`Command failed: ${cmd}`);
    throw err;
  }
}

function buildTarget(target) {
  console.log(`\n=== Building ${target.platform}-${target.arch} ===\n`);

  const nativeDir = path.join(ROOT, 'native', `${target.platform}-${target.arch}`);
  fs.mkdirSync(nativeDir, { recursive: true });

  const binaryName = target.platform === 'win32' ? 'swarmhack.exe' : 'swarmhack';
  const binaryPath = path.join(nativeDir, binaryName);

  // Build with cross-compilation
  try {
    exec(`cross build --release --target ${target.rust_target}`);

    const srcBinary = path.join(
      PROJECT_ROOT,
      'target',
      target.rust_target,
      'release',
      binaryName
    );

    fs.copyFileSync(srcBinary, binaryPath);
    fs.chmodSync(binaryPath, 0o755);
    console.log(`✓ Built: ${binaryPath}`);

  } catch (err) {
    console.warn(`⚠ Skipping ${target.rust_target}: ${err.message}`);
  }
}

function buildLocal() {
  console.log('\n=== Building for current platform ===\n');

  const platform = process.platform;
  const arch = process.arch;

  const nativeDir = path.join(ROOT, 'native', `${platform}-${arch}`);
  fs.mkdirSync(nativeDir, { recursive: true });

  const binaryName = platform === 'win32' ? 'swarmhack.exe' : 'swarmhack';

  exec('cargo build --release');

  const srcBinary = path.join(PROJECT_ROOT, 'target', 'release', binaryName);
  const destBinary = path.join(nativeDir, binaryName);

  fs.copyFileSync(srcBinary, destBinary);
  fs.chmodSync(destBinary, 0o755);

  console.log(`✓ Built: ${destBinary}`);
}

function main() {
  const args = process.argv.slice(2);

  if (args.includes('--all')) {
    // Build all platforms (requires cross)
    console.log('Building all platforms...');
    for (const target of TARGETS) {
      try {
        buildTarget(target);
      } catch (err) {
        console.error(`Failed to build ${target.platform}-${target.arch}`);
      }
    }
  } else {
    // Build for current platform only
    buildLocal();
  }

  console.log(`\n✓ Build complete! Version: ${VERSION}\n`);
  console.log('To publish:');
  console.log('  cd npm && npm publish --access public\n');
}

main();
