/**
 * Main entry point for the AI Interactive Fiction application
 */

import * as path from 'path';
import * as dotenv from 'dotenv';
import { GameRunner } from './cli/game-runner';
// Import the server module and the startServer function for the web interface
import { startServer } from './server';
import { loadGameConfig, projectPath } from './config/game-config';

// Load environment variables
console.log('Loading environment variables...');
try {
  const result = dotenv.config();
  if (result.error) {
    console.error('Error loading .env file:', result.error);
  } else {
    console.log('Environment variables loaded successfully');
  }
} catch (error) {
  console.error('Exception when loading env:', error);
}

async function main(): Promise<void> {
  try {
    console.log('=== AI Interactive Fiction ===');
    console.log('A modern take on classic text adventures with LLM-powered interactions');
    console.log('');

    // Get the world file path from the YAML engine config, with environment override.
    const engineConfig = loadGameConfig(
      process.env.YAML_CONFIG_FILE || './config/engines/yaml.json',
      'yaml',
    );
    const worldFile = projectPath(process.env.DEFAULT_WORLD_FILE || engineConfig.paths.mainGameFile);
    console.log(`Using world file: ${worldFile}`);
    console.log(`OpenRouter API Key: ${process.env.OPENROUTER_API_KEY ? '✓ Found' : '✗ Missing'}`);
    console.log(`OpenRouter Model: ${process.env.OPENROUTER_MODEL || '✗ Not specified'}`);
    
    // Check if we should run in CLI mode
    const args = process.argv.slice(2);
    const cliMode = args.includes('--cli') || args.includes('-c');
    
    if (cliMode) {
      // CLI mode
      console.log('Starting in CLI mode...');
      
      // Create game runner and initialize
      console.log('Creating game runner...');
      const gameRunner = new GameRunner();
      
      console.log('Initializing game...');
      await gameRunner.initialize(worldFile);
      
      // Start the CLI game
      console.log('Starting CLI game...');
      await gameRunner.start();
    } else {
      // Web interface mode - explicitly start the server with port fallback
      console.log('Starting in web interface mode...');
      
      // Get port configuration
      const DEFAULT_PORT = 3000;
      const PORT = process.env.PORT ? parseInt(process.env.PORT) : DEFAULT_PORT;
      const PORT_RANGE = 300;
      
      // Start the web server with port fallback
      console.log('Starting web server...');
      await startServer(PORT, PORT_RANGE);
    }
  } catch (error) {
    console.error('Failed to start:', error);
    if (error instanceof Error) {
      console.error('Error name:', error.name);
      console.error('Error message:', error.message);
      console.error('Error stack:', error.stack);
    }
    process.exit(1);
  }
}

// Start the application
console.log('Starting application...');
main().catch(error => {
  console.error('Unhandled error in main:', error);
  process.exit(1);
});
