const express = require('express');
const path = require('path');

// Simple logging utility with level control
const logger = {
  debug: (...args) => {
    if (process.env.LOG_LEVEL === 'debug' || process.env.NODE_ENV === 'development') {
      console.log('[DEBUG]', ...args);
    }
  },
  info: (...args) => console.log('[INFO]', ...args),
  warn: (...args) => console.warn('[WARN]', ...args),
  error: (...args) => console.error('[ERROR]', ...args)
};

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

// Serve static files from public directory
app.use(express.static(path.join(__dirname, 'public')));

// Health check endpoint (before catch-all route)
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    service: 'spore-ui-frontend',
    timestamp: new Date().toISOString(),
    note: 'Frontend server - API calls are handled by spore-gateway on port 3001'
  });
});

// SPA catch-all route - serves index.html for all routes
// This allows client-side routing to work properly
// Using regex pattern for Express 5 compatibility
app.get(/^\/(?!health$).*/, (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Start the server
app.listen(PORT, '0.0.0.0', () => {
  console.log(`SPORE UI Frontend Server is running on http://0.0.0.0:${PORT}`);
  console.log(`Accessible from: http://YOUR_COMPUTER_IP:${PORT}`);
  console.log(`Frontend connects to spore-gateway for API and WebSocket functionality`);
  console.log(`Make sure spore-gateway is running on port 3001`);
});