#!/usr/bin/env node

/**
 * Pack local binary for npm
 * Use this when you already have a built binary
 */

const fs = require('fs');
const path = require('path');
const os = require('os');

const ROOT = path.join(__dirname, '..');
const RELEASE_DIR = path.join(ROOT, '..');

function main() {
  const platform = os.platform();
  const arch = os.arch();
  const binaryName = platform === 'win32' ? 'swarmhack.exe' : 'swarmhack';

  // Source: release/swarmhack
  const srcBinary = path.join(RELEASE_DIR, 'swarmhack');

  if (!fs.existsSync(srcBinary)) {
    console.error(`Binary not found: ${srcBinary}`);
    console.error('Build first with: cargo build --release && cp target/release/swarmhack release/');
    process.exit(1);
  }

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

  const destBinary = path.join(nativeDir, binaryName);
  fs.copyFileSync(srcBinary, destBinary);
  fs.chmodSync(destBinary, 0o755);

  console.log(`✓ Packed binary for ${platform}-${arch}`);
  console.log(`  Source: ${srcBinary}`);
  console.log(`  Dest: ${destBinary}`);
  console.log();
  console.log('Package structure:');
  console.log('  npm/');
  console.log('  ├── package.json');
  console.log('  ├── bin/swarmhack.js');
  console.log('  ├── index.js');
  console.log(`  └── native/${platform}-${arch}/${binaryName}`);
  console.log();
  console.log('To test locally:');
  console.log('  cd npm && npm link');
  console.log('  swarmhack --version');
  console.log();
  console.log('To publish:');
  console.log('  cd npm && npm publish --access public');
}

main();
