const express = require('express');
const axios = require('axios');
const DatabaseService = require('../services/databaseService');
const logger = require('../utils/logger');

// Create database service instance
const databaseService = new DatabaseService();

const router = express.Router();

// Health check endpoint
router.get('/', async (req, res) => {
  try {
    const startTime = Date.now();
    
    // Check external services
    const externalServices = {
      techStackSelector: process.env.TECH_STACK_SELECTOR_HEALTH_URL || 'http://tech-stack-selector:8002/health',
      templateManager: process.env.TEMPLATE_MANAGER_HEALTH_URL || 'http://template-manager:8009/health'
    };

    const healthChecks = {};
    let allHealthy = true;

    // Check database health
    const databaseHealthy = await databaseService.isHealthy();
    if (!databaseHealthy) {
      allHealthy = false;
    }

    // Check each external service
    for (const [serviceName, url] of Object.entries(externalServices)) {
      try {
        const serviceStartTime = Date.now();
        const response = await axios.get(url, {
          timeout: parseInt(process.env.HEALTH_CHECK_TIMEOUT) || 5000,
          headers: {
            'User-Agent': 'Unison-HealthCheck/1.0'
          }
        });
        
        const responseTime = Date.now() - serviceStartTime;
        
        healthChecks[serviceName] = {
          status: 'healthy',
          responseTime: `${responseTime}ms`,
          statusCode: response.status,
          lastChecked: new Date().toISOString(),
          data: response.data
        };
      } catch (error) {
        allHealthy = false;
        healthChecks[serviceName] = {
          status: 'unhealthy',
          error: error.message,
          statusCode: error.response?.status || 'timeout',
          lastChecked: new Date().toISOString()
        };
        
        logger.warn({
          message: `External service ${serviceName} health check failed`,
          service: serviceName,
          url: url,
          error: error.message,
          statusCode: error.response?.status
        });
      }
    }

    const totalResponseTime = Date.now() - startTime;
    const overallStatus = allHealthy ? 'healthy' : 'degraded';

    const healthResponse = {
      status: overallStatus,
      service: 'unison',
      version: '1.0.0',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      responseTime: `${totalResponseTime}ms`,
      environment: process.env.NODE_ENV || 'development',
      memory: {
        used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024) + ' MB',
        total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024) + ' MB',
        external: Math.round(process.memoryUsage().external / 1024 / 1024) + ' MB'
      },
      externalServices: healthChecks,
      database: {
        status: databaseHealthy ? 'healthy' : 'unhealthy',
        type: 'PostgreSQL'
      },
      features: {
        unifiedRecommendations: true,
        techStackSelector: healthChecks.techStackSelector?.status === 'healthy',
        templateManager: healthChecks.templateManager?.status === 'healthy',
        claudeAI: !!process.env.CLAUDE_API_KEY,
        databaseStorage: databaseHealthy
      }
    };

    const statusCode = allHealthy ? 200 : 503;
    res.status(statusCode).json(healthResponse);

  } catch (error) {
    logger.error({
      message: 'Health check failed',
      error: error.message,
      stack: error.stack
    });

    res.status(500).json({
      status: 'unhealthy',
      service: 'unison',
      error: 'Health check failed',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

// Detailed health check with more information
router.get('/detailed', async (req, res) => {
  try {
    const detailedHealth = {
      status: 'healthy',
      service: 'unison',
      version: '1.0.0',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      environment: process.env.NODE_ENV || 'development',
      nodeVersion: process.version,
      platform: process.platform,
      architecture: process.arch,
      memory: process.memoryUsage(),
      cpu: process.cpuUsage(),
      pid: process.pid,
      config: {
        port: process.env.PORT || 8010,
        host: process.env.HOST || '0.0.0.0',
        techStackSelectorUrl: process.env.TECH_STACK_SELECTOR_URL,
        templateManagerUrl: process.env.TEMPLATE_MANAGER_URL,
        claudeApiKey: process.env.CLAUDE_API_KEY ? 'configured' : 'not configured'
      }
    };

    res.json(detailedHealth);
  } catch (error) {
    logger.error({
      message: 'Detailed health check failed',
      error: error.message
    });

    res.status(500).json({
      status: 'unhealthy',
      error: 'Detailed health check failed',
      message: error.message
    });
  }
});

module.exports = router;
