import express from 'express';
import compression from 'compression';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import optionsFlowRouter from './routes/optionsFlow.js';
import dailyAnalysisRouter from './routes/dailyAnalysis.js';
import pricesRouter from './routes/prices.js';
import stockPricesRouter from './routes/stockPrices.js';
import alertsRouter, { setupAlertsWebSocket } from './routes/alerts.js';
import scannerRouter from './routes/scanner.js';
import tradePlansRouter from './routes/tradePlans.js';
import performanceRouter from './routes/performance.js';
import reversalsRouter from './routes/reversals.js';
import convergenceRouter from './routes/convergence.js';
import marketAnalysisRouter from './routes/marketAnalysis.js';
import backtestRouter from './routes/backtest.js';
import healthRouter from './routes/health.js';
import { setupWebSocket } from './routes/websocket.js';
import { setupSecurity } from './middleware/security.js';
import { errorHandler } from './utils/errorHandler.js';
import { testConnection } from './db.js';
import { startPythonServiceHealthChecks, stopPythonServiceHealthChecks } from './middleware/pythonServiceHealth.js';
import { startCheddarFlowService, stopCheddarFlowService } from './services/cheddarflowWebSocketService.js';
import { startBookmapWebSocketService, stopBookmapWebSocketService } from './services/bookmapWebSocketService.js';

dotenv.config();

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

// Compression middleware
app.use(compression({
  filter: (req, res) => {
    if (req.headers['x-no-compression']) {
      return false;
    }
    return compression.filter(req, res);
  },
  level: 6,
}));

// Security middleware (helmet, CORS, rate limiting)
setupSecurity(app);

// Body parsing
app.use(express.json());

// Serve static frontend files in production
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const frontendPath = path.join(__dirname, '../../public');

// Static files MUST come before the wildcard catch-all
app.use(express.static(frontendPath, {
  maxAge: '1d',
  etag: true,
}));

// Routes
app.use('/api/options', optionsFlowRouter);
app.use('/api/analysis', dailyAnalysisRouter);
app.use('/api/prices', pricesRouter);
app.use('/api/stock-prices', stockPricesRouter);
app.use('/api/alerts', alertsRouter);
app.use('/api/scanner', scannerRouter);
app.use('/api/trade-plans', tradePlansRouter);
app.use('/api/performance', performanceRouter);
app.use('/api/reversals', reversalsRouter);
app.use('/api/convergence', convergenceRouter);
app.use('/api/market', marketAnalysisRouter);
app.use('/api/backtest', backtestRouter);
app.use('/health', healthRouter);

// SPA fallback — only for non-API, non-asset routes
app.get('*', (req, res, next) => {
  if (req.path.startsWith('/api/') || req.path.startsWith('/health') || req.path.startsWith('/assets/')) {
    return next();
  }
  const indexPath = path.join(frontendPath, 'index.html');
  res.sendFile(indexPath, (err) => {
    if (err) next(err);
  });
});

// Error handler (must be last)
app.use(errorHandler);

// Start server
const server = app.listen(PORT, async () => {
  console.log(`🚀 Server running on http://localhost:${PORT}`);
  console.log(`📍 Environment: ${process.env.NODE_ENV || 'development'}`);
  
  // Test database connection
  await testConnection();
  
  // Start Python service health checks
  if (process.env.USE_PYTHON_SERVICE !== 'false') {
    console.log('🐍 Starting Python service health checks...');
    startPythonServiceHealthChecks();
  } else {
    console.log('📊 Python service disabled (USE_PYTHON_SERVICE=false)');
  }

  // Start CheddarFlow WebSocket service
  if (process.env.ENABLE_CHEDDARFLOW === 'true') {
    console.log('📡 Starting CheddarFlow live option flow service...');
    startCheddarFlowService({
      enableDatabaseInsert: process.env.CHEDDARFLOW_SAVE_TO_DB !== 'false',
      autoReconnect: true,
      reconnectInterval: 5000,
      maxReconnectAttempts: 10
    });
  } else {
    console.log('📡 CheddarFlow service disabled (set ENABLE_CHEDDARFLOW=true to enable)');
  }

  // Start Bookmap WebSocket service (receives data from Bookmap add-on)
  if (process.env.ENABLE_BOOKMAP !== 'false') {
    const bookmapPort = parseInt(process.env.BOOKMAP_WS_PORT || '3001');
    console.log(`📊 Starting Bookmap WebSocket service on port ${bookmapPort}...`);
    const bookmapWss = startBookmapWebSocketService(bookmapPort);
    // Store reference for graceful shutdown
    app.locals.bookmapWss = bookmapWss;
  } else {
    console.log('📊 Bookmap service disabled (set ENABLE_BOOKMAP=false to disable)');
  }
});

// Setup WebSocket
setupWebSocket(server);
setupAlertsWebSocket(server);

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully...');
  stopPythonServiceHealthChecks();
  stopCheddarFlowService();
  if (app.locals.bookmapWss) {
    stopBookmapWebSocketService(app.locals.bookmapWss);
  }
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  console.log('SIGINT received, shutting down gracefully...');
  stopPythonServiceHealthChecks();
  stopCheddarFlowService();
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
});
