/**
 * Middleware to check Python service health and log status
 */
import { checkPythonServiceHealth as checkHealth } from '../services/pythonServiceClient.js';

// Re-export for use in other modules
export { checkPythonServiceHealth } from '../services/pythonServiceClient.js';

let lastHealthCheck = null;
let healthCheckInterval = null;
let lastLoggedState = null; // Track last logged state to avoid spam
const HEALTH_CHECK_INTERVAL = 60000; // 1 minute

/**
 * Start periodic health checks for Python service
 */
export function startPythonServiceHealthChecks() {
  if (healthCheckInterval) {
    return; // Already running
  }

  // Initial check
  performHealthCheck();

  // Periodic checks
  healthCheckInterval = setInterval(performHealthCheck, HEALTH_CHECK_INTERVAL);
}

/**
 * Stop periodic health checks
 */
export function stopPythonServiceHealthChecks() {
  if (healthCheckInterval) {
    clearInterval(healthCheckInterval);
    healthCheckInterval = null;
  }
}

/**
 * Perform a health check
 */
async function performHealthCheck() {
  try {
    const isHealthy = await checkHealth();
    const previousState = lastHealthCheck?.healthy;
    
    lastHealthCheck = {
      timestamp: new Date(),
      healthy: isHealthy
    };

    // Only log when state changes to avoid spam
    if (isHealthy) {
      if (previousState !== true) {
        console.log('✅ Python service is healthy');
        lastLoggedState = 'healthy';
      }
    } else {
      // Only log failure if state changed or if we haven't logged in a while
      const timeSinceLastLog = lastHealthCheck.timestamp - (lastHealthCheck.lastLogTime || 0);
      if (previousState !== false || timeSinceLastLog > 300000) { // Log every 5 minutes if continuously failing
        console.warn('⚠️  Python service health check failed - service may not be running');
        console.warn('   To start the Python service, run: cd backend/python_service && uvicorn main:app --reload --port 8010');
        lastLoggedState = 'unhealthy';
        lastHealthCheck.lastLogTime = lastHealthCheck.timestamp;
      }
    }
  } catch (error) {
    const previousState = lastHealthCheck?.healthy;
    lastHealthCheck = {
      timestamp: new Date(),
      healthy: false,
      error: error.message
    };
    
    // Only log error if state changed
    if (previousState !== false) {
      console.error('❌ Python service health check error:', error.message);
      console.error('   Ensure the Python service is running at http://localhost:8010');
    }
  }
}

/**
 * Get last health check status
 */
export function getPythonServiceHealth() {
  return lastHealthCheck;
}

/**
 * Middleware to log Python service usage
 */
export function pythonServiceLogger(req, res, next) {
  const startTime = Date.now();
  
  // Override res.json to log response time
  const originalJson = res.json.bind(res);
  res.json = function(data) {
    const duration = Date.now() - startTime;
    
    if (data.success && data.metadata?.source === 'python') {
      console.log(`🐍 Python service: ${req.path} - ${duration}ms - ${data.count || 0} rows`);
    } else if (data.success && data.metadata?.source === 'sql') {
      console.log(`📊 SQL fallback: ${req.path} - ${duration}ms - ${data.count || 0} rows`);
    }
    
    return originalJson(data);
  };
  
  next();
}

