#!/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() {
  console.log('Starting Claude Code Web...');
  
  // Check if .output directory exists (production build)
  const outputDir = join(projectRoot, '.output');
  try {
    await access(outputDir);
    console.log('Starting production server...');
    
    // 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('\nShutting down Claude Code Web...');
      server.kill('SIGINT');
    });

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

  } catch (error) {
    console.error('Production build not found. Please run "npm run build" first.');
    console.error('Alternatively, run "npm run dev" for development mode.');
    process.exit(1);
  }
}

startServer();