#!/usr/bin/env node

import { spawn } from 'child_process';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { access } from 'fs/promises';

const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = join(__dirname, '..');

async function startServer() {
  // Check if .output directory exists (production build)
  const outputDir = join(projectRoot, '.output');
  try {
    await access(outputDir);
    let host = process.env.HOST || '0.0.0.0';
    let port = process.env.PORT || '3000';
    console.log(`🚀 Starting claude-code-web on ${host}:${port}`)
    console.log('📦 Node version:', process.version)
    
    // Start the production server
    const server = spawn('node', [join(outputDir, 'server', 'index.mjs')], {
      stdio: 'inherit',
      cwd: projectRoot,
      env: {
        ...process.env,
        NODE_ENV: 'production',
        PORT: process.env.PORT || '3000',
        HOST: process.env.HOST || '0.0.0.0'
      }
    });

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

    server.on('exit', (code) => {
      process.exit(code || 0);
    });

    // Handle graceful shutdown
    process.on('SIGINT', () => {
      console.log('\n🛑 Shutting down Claude Code Web...');
      server.kill('SIGINT');
    });

    process.on('SIGTERM', () => {
      console.log('\n🛑 Shutting down Claude Code Web...');
      server.kill('SIGTERM');
    });

  } catch (error) {
    console.error('❌ Error starting server:', error)
    process.exit(1);
  }
}

startServer();