/**
 * AI Service Health Check
 *
 * Provides health monitoring for DashScope AI service with caching and timeout handling.
 */

import { aiConfig } from './ai';
import { logger } from '../shared/utils/logger';

/**
 * AI Health Status
 */
export interface AIHealthStatus {
  status: 'ok' | 'degraded' | 'error';
  model: string;
  latency: number | null;
  lastChecked: string;
  error?: string;
}

/**
 * Cached health check result
 */
interface CachedHealthResult {
  result: AIHealthStatus;
  timestamp: number;
}

/**
 * Cache duration in milliseconds (30 seconds)
 */
const CACHE_DURATION_MS = 30000;

/**
 * Health check timeout in milliseconds (5 seconds)
 */
const HEALTH_CHECK_TIMEOUT_MS = 5000;

/**
 * Degraded latency threshold in milliseconds (3 seconds)
 */
const DEGRADED_LATENCY_MS = 3000;

/**
 * Cached result for AI health
 */
let cachedHealthResult: CachedHealthResult | null = null;

/**
 * Check AI service health with caching and timeout
 *
 * - Timeout: 5 seconds to avoid blocking health endpoint
 * - Cache: 30 seconds to reduce API calls
 * - Degraded: latency > 3 seconds
 */
export async function checkAIHealth(): Promise<AIHealthStatus> {
  const now = Date.now();

  // Return cached result if still valid
  if (cachedHealthResult && (now - cachedHealthResult.timestamp) < CACHE_DURATION_MS) {
    logger.debug('Returning cached AI health result');
    return cachedHealthResult.result;
  }

  // Get model info
  const modelInfo = aiConfig.getModelInfo();

  // Create timeout promise
  const timeoutPromise = new Promise<never>((_, reject) => {
    setTimeout(() => {
      reject(new Error('Health check timeout'));
    }, HEALTH_CHECK_TIMEOUT_MS);
  });

  try {
    // Measure latency
    const startTime = Date.now();

    // Run health check with timeout
    const healthPromise = aiConfig.healthCheck();

    const isHealthy = await Promise.race([healthPromise, timeoutPromise]);

    const latency = Date.now() - startTime;
    const lastChecked = new Date().toISOString();

    // Determine status based on latency
    let status: 'ok' | 'degraded' | 'error';
    if (!isHealthy) {
      status = 'error';
    } else if (latency > DEGRADED_LATENCY_MS) {
      status = 'degraded';
    } else {
      status = 'ok';
    }

    const result: AIHealthStatus = {
      status,
      model: modelInfo.model,
      latency,
      lastChecked,
    };

    // Cache the result
    cachedHealthResult = {
      result,
      timestamp: now,
    };

    logger.debug({
      status,
      latency,
      model: modelInfo.model,
    }, 'AI health check completed');

    return result;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    const lastChecked = new Date().toISOString();

    const result: AIHealthStatus = {
      status: 'error',
      model: modelInfo.model,
      latency: null,
      lastChecked,
      error: errorMessage,
    };

    // Cache the error result too (but with shorter cache to retry sooner)
    cachedHealthResult = {
      result,
      timestamp: now - (CACHE_DURATION_MS - 5000), // Cache for only 5 seconds on error
    };

    logger.warn({
      error: errorMessage,
      model: modelInfo.model,
    }, 'AI health check failed');

    return result;
  }
}

/**
 * Clear the cached health result
 */
export function clearAIHealthCache(): void {
  cachedHealthResult = null;
}