import { createApp, appConfig } from './app';
import fs from 'fs';
import path from 'path';

// Ensure required directories exist
const ensureDirectoriesExist = () => {
  const directories = [
    appConfig.resultsDir,
    appConfig.uploadsDir,
    './logs'
  ];

  directories.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      console.log(`[${new Date().toISOString()}] Created directory: ${dir}`);
    }
  });
};

// Enhanced logging function
const log = (level: 'INFO' | 'ERROR' | 'WARN' | 'DEBUG', message: string) => {
  const timestamp = new Date().toISOString();
  const logMessage = `[${timestamp}] [${level}] ${message}`;
  console.log(logMessage);
};

// Validate environment
const validateEnvironment = () => {
  if (!appConfig.geminiApiKey) {
    log('ERROR', 'GEMINI_API_KEY environment variable is required');
    process.exit(1);
  }

  log('INFO', 'Environment validation passed');
  log('INFO', `Server configuration: port=${appConfig.port}, maxFileSize=${appConfig.maxFileSize}bytes, maxFiles=${appConfig.maxFiles}`);
};

// Graceful shutdown
const setupGracefulShutdown = (server: any) => {
  const shutdown = (signal: string) => {
    log('INFO', `Received ${signal}, shutting down gracefully...`);

    server.close((err: Error) => {
      if (err) {
        log('ERROR', `Error during shutdown: ${err.message}`);
        process.exit(1);
      }
      log('INFO', 'Server closed successfully');
      process.exit(0);
    });
  };

  process.on('SIGTERM', () => shutdown('SIGTERM'));
  process.on('SIGINT', () => shutdown('SIGINT'));
};

// Start server
const startServer = async () => {
  try {
    log('INFO', '🚀 Starting Magic Building Image Generation Server...');

    // Validate environment and create directories
    validateEnvironment();
    ensureDirectoriesExist();

    // Create Express app
    const app = createApp();

    // Start server
    const server = app.listen(appConfig.port, () => {
      log('INFO', `✅ Server running on port ${appConfig.port}`);
      log('INFO', `📋 Health check: http://localhost:${appConfig.port}/health`);
      log('INFO', `📖 API info: http://localhost:${appConfig.port}/api/info`);
      log('INFO', `🎨 Generate endpoint: http://localhost:${appConfig.port}/api/generate`);
    });

    // Setup graceful shutdown
    setupGracefulShutdown(server);

  } catch (error) {
    log('ERROR', `Failed to start server: ${error instanceof Error ? error.message : error}`);
    process.exit(1);
  }
};

// Start the server
startServer();