import { logger } from '../../utils/logger';
import db from '../../config/database';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';

export interface HealthMetric {
  tenantId: string;
  metricName: string;
  currentValue: number;
  predictedValue: number;
  trend: 'STABLE' | 'UPWARD' | 'DOWNWARD';
  riskScore: number; // 0-100
}

/**
 * [CORE_TELE_PREDICTIVE_HEALTH] 预测性系统健康度看板 (Predictive Health)
 * @description 核心逻辑：利用时间序列分析与简单的回归模型，预测系统未来的健康状况。
 * 通过监控 CPU、内存、API 延迟以及租户请求量，识别潜在的资源枯竭或性能雪崩风险，
 * 在故障发生前 15-30 分钟触发预警与自动扩容建议。
 */
export class PredictiveHealthService {
  private static readonly METRIC_TABLE = 'cf_system_health_metrics';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.METRIC_TABLE);
    if (!hasTable) {
      logger.info('📦 Creating cf_system_health_metrics table...');
      await db.schema.createTable(this.METRIC_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('metric_name', 64).notNullable();
        table.float('metric_value').notNullable();
        table.timestamp('timestamp').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 记录系统指标
   */
  static async recordMetric(tenantId: string, name: string, value: number) {
    try {
      await db(this.METRIC_TABLE).insert({
        tenant_id: tenantId,
        metric_name: name,
        metric_value: value,
        timestamp: new Date()
      });
    } catch (err: any) {
      logger.error(`[PredictiveHealth] Failed to record metric: ${err.message}`);
    }
  }

  /**
   * 预测未来 24 小时健康状况 (基于 24h 历史趋势)
   */
  static async predictHealth(tenantId: string): Promise<HealthMetric[]> {
    if (!(await FeatureGovernanceService.isEnabled('CORE_TELE_PREDICTIVE_HEALTH', tenantId))) {
      return [];
    }

    // 1. 获取过去 24 小时的指标数据
    const dayAgo = new Date(Date.now() - 86400000);
    const metrics = await db(this.METRIC_TABLE)
      .where({ tenant_id: tenantId })
      .andWhere('timestamp', '>=', dayAgo)
      .orderBy('timestamp', 'asc');

    const results: HealthMetric[] = [];
    const metricTypes = ['API_LATENCY', 'CPU_USAGE', 'MEMORY_USAGE', 'REQUEST_COUNT'];

    for (const type of metricTypes) {
      const typeMetrics = metrics.filter(m => m.metric_name === type);
      if (typeMetrics.length < 2) continue;

      const latest = typeMetrics[typeMetrics.length - 1].metric_value;
      const earliest = typeMetrics[0].metric_value;
      
      // 简单线性回归斜率: (y2 - y1) / (x2 - x1)
      const slope = (latest - earliest) / (typeMetrics.length);
      
      // 预测 24h 后的值 (假设数据点是均匀分布的)
      const predictedValue = latest + (slope * typeMetrics.length);
      
      const trend = predictedValue > latest ? 'UPWARD' : (predictedValue < latest ? 'DOWNWARD' : 'STABLE');
      
      // 风险评分逻辑
      let riskScore = 0;
      if (type === 'API_LATENCY') riskScore = predictedValue > 1000 ? 90 : (predictedValue > 500 ? 50 : 10);
      if (type === 'CPU_USAGE' || type === 'MEMORY_USAGE') riskScore = predictedValue > 90 ? 95 : (predictedValue > 70 ? 60 : 10);
      if (type === 'REQUEST_COUNT') riskScore = predictedValue > latest * 2 ? 70 : 10;

      results.push({
        tenantId,
        metricName: type,
        currentValue: latest,
        predictedValue: Number(predictedValue.toFixed(2)),
        trend,
        riskScore
      });
    }

    return results;
  }
}
