require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');

const generateRoutes = require('./api/generate');
const cacheRoutes = require('./api/cache');

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// Routes - handle both root and /CompareKit paths
app.use(['/api/generate', '/CompareKit/api/generate'], generateRoutes);
app.use(['/api/cache', '/CompareKit/api/cache'], cacheRoutes);

// Health check - handle both paths
app.get(['/health', '/CompareKit/health'], (req, res) => {
  res.json({
    status: 'ok',
    service: 'CompareKit',
    version: '1.0.0'
  });
});

// Serve frontend - handle both paths
app.get(['/', '/CompareKit', '/CompareKit/'], (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    error: 'Not found'
  });
});

// Error handler
app.use((err, req, res, next) => {
  console.error('Server error:', err);
  res.status(500).json({
    error: 'Internal server error',
    message: err.message
  });
});

// Start server - CloudLinux Passenger needs explicit listen() call
app.listen(PORT, () => {
  console.log('');
  console.log('╔════════════════════════════════════════╗');
  console.log('║         CompareKit Server              ║');
  console.log('║   Professional Image Generator         ║');
  console.log('╚════════════════════════════════════════╝');
  console.log('');
  console.log(`🚀 Server running on http://localhost:${PORT}`);
  console.log(`📖 API Docs: http://localhost:${PORT}/api`);
  console.log(`🎨 Test Interface: http://localhost:${PORT}`);
  console.log('');
  console.log('Available endpoints:');
  console.log('  POST /api/generate/comparison - Generate single image');
  console.log('  POST /api/generate/batch - Generate multiple images');
  console.log('  GET  /api/generate/styles - Get available styles');
  console.log('  GET  /api/cache/stats - Get cache statistics');
  console.log('  DELETE /api/cache/logos - Clear logo cache');
  console.log('');
});
