#!/usr/bin/env node

/**
 * Build script for Insertr unified binary
 * This ensures the unified binary always has the latest library version embedded
 */

import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';

console.log('🔨 Building Insertr unified binary...\n');

// 1. Build the library
console.log('📦 Building JavaScript library...');
try {
    execSync('npm run build', { cwd: 'lib', stdio: 'inherit' });
    console.log('✅ Library built successfully\n');
} catch (error) {
    console.error('❌ Library build failed:', error.message);
    process.exit(1);
}

// 2. Copy built library to unified binary assets
console.log('📁 Copying library to unified binary assets...');
const srcDir = './lib/dist';
const destDir = './internal/content/assets';

// Ensure destination directory exists
fs.mkdirSync(destDir, { recursive: true });

// Copy files
const files = fs.readdirSync(srcDir);
files.forEach(file => {
    const src = path.join(srcDir, file);
    const dest = path.join(destDir, file);
    fs.copyFileSync(src, dest);
    console.log(`  ✅ Copied ${file}`);
});

console.log('📁 Assets copied successfully\n');

// 3. Build the unified binary
console.log('🔧 Building unified Insertr binary...');
try {
    execSync('go build -o insertr .', { stdio: 'inherit' });
    console.log('✅ Unified binary built successfully\n');
} catch (error) {
    console.error('❌ Unified binary build failed:', error.message);
    process.exit(1);
}

console.log('🎉 Build complete!\n');
console.log('📋 What was built:');
console.log('  • JavaScript library (lib/dist/)');
console.log('  • Unified Insertr binary with embedded library (./insertr)');
console.log('\n🚀 Ready to use:');
console.log('  just dev         # Full-stack development');
console.log('  just serve       # API server only');
console.log('  ./insertr --help # See all commands');