#!/usr/bin/env node

/**
 * SwarmHack Postinstall Script
 * Downloads the appropriate binary for the current platform
 */

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

const VERSION = '0.1.0';
const GITHUB_REPO = 'prancer-io/swarmhack';
const BASE_URL = `https://github.com/${GITHUB_REPO}/releases/download/v${VERSION}`;

// Platform mapping
const PLATFORM_MAP = {
  'linux-x64': 'swarmhack-linux-x64',
  'linux-arm64': 'swarmhack-linux-arm64',
  'darwin-x64': 'swarmhack-darwin-x64',
  'darwin-arm64': 'swarmhack-darwin-arm64',
  'win32-x64': 'swarmhack-windows-x64.exe',
};

function getPlatformKey() {
  const platform = os.platform();
  const arch = os.arch();
  return `${platform}-${arch}`;
}

function getBinaryName() {
  const platform = os.platform();
  return platform === 'win32' ? 'swarmhack.exe' : 'swarmhack';
}

function downloadFile(url, dest) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(dest);

    const request = https.get(url, (response) => {
      // Handle redirects (GitHub releases use redirects)
      if (response.statusCode === 302 || response.statusCode === 301) {
        file.close();
        fs.unlinkSync(dest);
        return downloadFile(response.headers.location, dest).then(resolve).catch(reject);
      }

      if (response.statusCode !== 200) {
        file.close();
        fs.unlinkSync(dest);
        reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`));
        return;
      }

      response.pipe(file);
      file.on('finish', () => {
        file.close();
        resolve();
      });
    });

    request.on('error', (err) => {
      file.close();
      fs.unlinkSync(dest);
      reject(err);
    });

    request.setTimeout(60000, () => {
      request.destroy();
      reject(new Error('Download timeout'));
    });
  });
}

async function main() {
  const platformKey = getPlatformKey();
  const remoteBinary = PLATFORM_MAP[platformKey];

  const nativeDir = path.join(__dirname, '..', 'native', platformKey);
  const binaryPath = path.join(nativeDir, getBinaryName());

  // Skip if already exists (bundled in package)
  if (fs.existsSync(binaryPath)) {
    // Make sure it's executable
    if (os.platform() !== 'win32') {
      try {
        fs.chmodSync(binaryPath, 0o755);
      } catch (e) {
        // Ignore permission errors
      }
    }
    console.log(`✓ SwarmHack binary ready: ${binaryPath}`);
    return;
  }

  if (!remoteBinary) {
    console.log(`
╔════════════════════════════════════════════════════════════╗
║  SwarmHack: Platform not supported                         ║
╠════════════════════════════════════════════════════════════╣
║  Your platform: ${platformKey.padEnd(40)}║
║                                                            ║
║  Supported platforms:                                      ║
║    - linux-x64, linux-arm64                                ║
║    - darwin-x64, darwin-arm64                              ║
║    - win32-x64                                             ║
║                                                            ║
║  Alternative: Use Docker                                   ║
║    docker run prancer/swarmhack:${VERSION} --help             ║
╚════════════════════════════════════════════════════════════╝
`);
    // Don't fail install - just warn
    return;
  }

  // Create directory
  fs.mkdirSync(nativeDir, { recursive: true });

  const url = `${BASE_URL}/${remoteBinary}`;

  console.log(`
╔════════════════════════════════════════════════════════════╗
║  SwarmHack: Downloading binary...                          ║
╠════════════════════════════════════════════════════════════╣
║  Version: ${VERSION.padEnd(48)}║
║  Platform: ${platformKey.padEnd(47)}║
╚════════════════════════════════════════════════════════════╝
`);

  try {
    await downloadFile(url, binaryPath);

    // Make executable on Unix
    if (os.platform() !== 'win32') {
      fs.chmodSync(binaryPath, 0o755);
    }

    console.log(`✓ SwarmHack installed successfully!`);
    console.log(`  Binary: ${binaryPath}`);
    console.log(`\n  Run: npx swarmhack --help\n`);

  } catch (err) {
    console.error(`
╔════════════════════════════════════════════════════════════╗
║  SwarmHack: Download failed                                ║
╠════════════════════════════════════════════════════════════╣
║  ${err.message.substring(0, 56).padEnd(56)}║
║                                                            ║
║  Manual installation:                                      ║
║  1. Download from GitHub releases                          ║
║  2. Place binary in: native/${platformKey}/                   ║
║  3. Make executable: chmod +x swarmhack                    ║
║                                                            ║
║  Or use Docker:                                            ║
║    docker run prancer/swarmhack:${VERSION} --help             ║
╚════════════════════════════════════════════════════════════╝
`);
    // Don't fail the install
  }
}

main().catch(console.error);
