#!/usr/bin/env node

/**
 * Build script for Ignite Memory components
 * Prepares memory system for distribution
 */

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

// Paths
const rootDir = path.join(__dirname, '..');
const memoryDir = path.join(rootDir, 'ignite', 'memory');
const distDir = path.join(memoryDir, 'dist');

// Create dist directory if it doesn't exist
if (!fs.existsSync(distDir)) {
  fs.mkdirSync(distDir, { recursive: true });
}

console.log('Building Ignite Memory components...\n');

// 1. Copy worker service
const workerSrc = path.join(memoryDir, 'worker', 'service.js');
const workerDest = path.join(distDir, 'worker-service.js');

if (fs.existsSync(workerSrc)) {
  fs.copyFileSync(workerSrc, workerDest);
  console.log('✓ Worker service copied');
} else {
  console.log('⚠ Worker service not found, creating placeholder...');
  // Create a minimal worker if the full one doesn't exist
  fs.writeFileSync(workerDest, `
// Placeholder worker service
const express = require('express');
const app = express();
app.get('/health', (req, res) => res.json({ status: 'ok' }));
if (require.main === module) {
  app.listen(process.env.IGNITE_MEMORY_PORT || 37777, () => {
    console.log('Ignite Memory Worker (placeholder) running');
  });
}
module.exports = app;
  `.trim());
}

// 2. Copy library files
const libFiles = ['memory-bridge.js', 'session-manager.js', 'context-enricher.js'];
const libDir = path.join(memoryDir, 'lib');
const libDest = path.join(distDir, 'lib');

if (!fs.existsSync(libDest)) {
  fs.mkdirSync(libDest, { recursive: true });
}

libFiles.forEach(file => {
  const src = path.join(libDir, file);
  const dest = path.join(libDest, file);

  if (fs.existsSync(src)) {
    fs.copyFileSync(src, dest);
    console.log(`✓ ${file} copied`);
  } else {
    console.log(`⚠ ${file} not found`);
  }
});

// 3. Copy database schemas
const schemaFile = path.join(memoryDir, 'database', 'ignite-schema.sql');
const schemaDest = path.join(distDir, 'schema.sql');

if (fs.existsSync(schemaFile)) {
  fs.copyFileSync(schemaFile, schemaDest);
  console.log('✓ Database schema copied');
} else {
  console.log('⚠ Database schema not found');
}

// 4. Copy UI files
const uiSrc = path.join(memoryDir, 'ui', 'index.html');
const uiDest = path.join(distDir, 'ui');

if (!fs.existsSync(uiDest)) {
  fs.mkdirSync(uiDest, { recursive: true });
}

if (fs.existsSync(uiSrc)) {
  fs.copyFileSync(uiSrc, path.join(uiDest, 'index.html'));
  console.log('✓ UI files copied');
} else {
  console.log('⚠ UI files not found');
}

// 5. Create package.json for the memory module
const memoryPackageJson = {
  name: '@ignite/memory',
  version: '1.0.0',
  description: 'Memory system for Ignite',
  main: 'lib/memory-bridge.js',
  scripts: {
    start: 'node worker-service.js'
  },
  dependencies: {
    'express': '^4.18.2',
    'better-sqlite3': '^9.2.2'
  }
};

fs.writeFileSync(
  path.join(distDir, 'package.json'),
  JSON.stringify(memoryPackageJson, null, 2)
);
console.log('✓ Memory package.json created');

// 6. Create a simple startup script
const startupScript = `#!/usr/bin/env node

/**
 * Ignite Memory Startup Script
 */

const path = require('path');
const { spawn } = require('child_process');

// Start the worker service
const workerPath = path.join(__dirname, 'worker-service.js');
const worker = spawn('node', [workerPath], {
  stdio: 'inherit',
  env: { ...process.env, IGNITE_MEMORY_PORT: process.env.PORT || 37777 }
});

worker.on('error', (err) => {
  console.error('Failed to start memory worker:', err);
  process.exit(1);
});

worker.on('exit', (code) => {
  process.exit(code);
});

console.log('Ignite Memory System starting...');
`;

fs.writeFileSync(
  path.join(distDir, 'start.js'),
  startupScript,
  { mode: 0o755 }
);
console.log('✓ Startup script created');

console.log('\n✅ Memory build complete!');
console.log(`   Output: ${distDir}`);