#!/usr/bin/env node

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

const GO_VERSION = '1.21.0';

// Build binary using go-bin
async function buildWithGoBin() {
  const platform = os.platform();
  const arch = os.arch();
  const goos = platform === 'win32' ? 'windows' : platform;
  const goarch = arch === 'x64' ? 'amd64' : arch === 'arm64' ? 'arm64' : arch;
  const binaryName = platform === 'win32' ? 'tanagram.exe' : 'tanagram';
  const binaryPath = path.join(__dirname, 'bin', binaryName);

  const binDir = path.join(__dirname, 'bin');
  if (!fs.existsSync(binDir)) {
    fs.mkdirSync(binDir, { recursive: true });
  }

  console.log('📦 Installing Go compiler via npm...');

  try {
    // Install Go using go-bin
    const goBin = require('go-bin');
    const goDir = await goBin({ version: GO_VERSION, dir: __dirname });
    const goPath = path.join(goDir, 'bin', 'go');

    console.log('🔧 Building Tanagram CLI...');

    // Build the binary using the downloaded Go
    execSync(`"${goPath}" build -o "${binaryPath}" .`, {
      cwd: __dirname,
      stdio: 'inherit',
      env: {
        ...process.env,
        GOOS: goos,
        GOARCH: goarch,
        GOROOT: goDir
      }
    });

    if (platform !== 'win32') {
      fs.chmodSync(binaryPath, '755');
    }

    // Clean up Go installation
    console.log('🧹 Cleaning up...');
    fs.rmSync(goDir, { recursive: true, force: true });

    console.log('✓ Tanagram CLI installed successfully');
    return true;
  } catch (error) {
    console.error('Failed to build with go-bin:', error.message);
    return false;
  }
}

// Main installation flow
(async () => {
  try {
    const built = await buildWithGoBin();
    if (!built) {
      console.error('\n❌ Installation failed');
      process.exit(1);
    }
    process.exit(0);
  } catch (error) {
    console.error('Installation error:', error.message);
    process.exit(1);
  }
})();
