#!/usr/bin/env node
/**
 * Post-install script: Build mk3-tui if Rust is available
 */

import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const mk3Dir = path.join(__dirname, '..', 'mk3-tui');
const binaryName = process.platform === 'win32' ? 'mk3-tui.exe' : 'mk3-tui';
const binaryPath = path.join(mk3Dir, 'target', 'release', binaryName);

// Check if binary already exists
if (fs.existsSync(binaryPath)) {
  console.log('✓ mk3-tui binary found');
  process.exit(0);
}

// Check if mk3-tui source exists
if (!fs.existsSync(mk3Dir)) {
  console.warn('⚠️  mk3-tui source not found in package');
  process.exit(0); // Not an error - might be dev mode
}

// Check if Rust is installed
try {
  execSync('cargo --version', { stdio: 'ignore' });
} catch {
  console.log('ℹ️  Rust not installed. mk3-tui will be built on first run if Rust is available.');
  process.exit(0);
}

// Try to build
try {
  console.log('🔨 Building mk3-tui...');
  execSync('cargo build --release', {
    cwd: mk3Dir,
    stdio: 'inherit',
  });
  console.log('✓ mk3-tui built successfully');
  
  // Clean up build artifacts to save disk space (~300-400MB)
  try {
    const cleanupScript = path.join(__dirname, 'cleanup-build-artifacts.js');
    if (fs.existsSync(cleanupScript)) {
      execSync(`node "${cleanupScript}"`, {
        cwd: path.dirname(__dirname),
        stdio: 'ignore', // Silent cleanup
      });
    }
  } catch {
    // Silent - cleanup is optional, don't fail if it doesn't work
  }
} catch (error) {
  console.warn('⚠️  Failed to build mk3-tui. It will be built on first run.');
  // Don't exit with error - allow install to complete
}

