#!/usr/bin/env node

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

// Platform mapping
const PLATFORMS = {
  darwin: 'darwin',
  linux: 'linux',
  win32: 'windows',
};

const ARCHS = {
  x64: 'amd64',
  arm64: 'arm64',
};

function getPlatformInfo() {
  const platform = PLATFORMS[process.platform];
  const arch = ARCHS[process.arch];

  if (!platform) {
    throw new Error(`Unsupported platform: ${process.platform}`);
  }
  if (!arch) {
    throw new Error(`Unsupported architecture: ${process.arch}`);
  }

  return { platform, arch };
}

function getBinaryName() {
  return process.platform === 'win32' ? 'gitlume-bin.exe' : 'gitlume-bin';
}

function getSourceBinaryName(platform, arch) {
  const ext = platform === 'windows' ? '.exe' : '';
  return `gitlume-bin-${platform}-${arch}${ext}`;
}

async function main() {
  try {
    const { platform, arch } = getPlatformInfo();
    const binDir = path.join(__dirname, '..', 'bin');
    const binariesDir = path.join(__dirname, '..', 'binaries');
    const binaryName = getBinaryName();
    const sourceBinaryName = getSourceBinaryName(platform, arch);

    const sourcePath = path.join(binariesDir, sourceBinaryName);
    const destPath = path.join(binDir, binaryName);

    // Check if binary already exists
    if (fs.existsSync(destPath)) {
      console.log('GitLume CLI binary already installed');
      return;
    }

    // Check if source binary exists
    if (!fs.existsSync(sourcePath)) {
      console.error('');
      console.error(`Binary not found for ${platform}-${arch}`);
      console.error(`Expected: ${sourcePath}`);
      console.error('');
      console.error('This platform may not be supported yet.');
      console.error('Please open an issue at: https://github.com/dnysus/git-lume/issues');
      console.error('');
      return;
    }

    // Create bin directory if needed
    fs.mkdirSync(binDir, { recursive: true });

    // Copy binary
    console.log(`Installing GitLume CLI for ${platform}-${arch}...`);
    fs.copyFileSync(sourcePath, destPath);

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

    console.log('');
    console.log('  GitLume CLI installed successfully!');
    console.log('');
    console.log('  Get started:');
    console.log('    1. Set your token: export GITLUME_TOKEN=gl_xxx');
    console.log('    2. Push your repo: gitlume push');
    console.log('');
  } catch (error) {
    console.error('');
    console.error('Failed to install GitLume CLI:', error.message);
    console.error('');
  }
}

main();
