import db from '../../config/database';
import { logger } from '../../utils/logger';
import { WebhookService } from '../../core/integrations/WebhookService';

export interface SLAMetric {
  tenantId: string;
  metricName: 'UPTIME' | 'API_LATENCY' | 'TASK_SUCCESS_RATE' | 'REQUEST_COUNT';
  targetValue?: number;
  currentValue: number;
  status?: 'HEALTHY' | 'VIOLATED';
}

/**
 * [CORE_TOB_06] 租户 SLA 治理与熔断服务
 * @description 实时监控租户请求质量，自动触发配额降级与熔断保护。
 * 整合了 [BIZ_GOV_08] 的实时达成度监控与 [CORE_TOB_06] 的自动熔断能力。
 */
export class SLAGovernanceService {
  private static readonly TABLE_NAME = 'cf_tenant_sla_status';

  /**
   * 记录指标并检查 SLA
   */
  static async recordMetric(metric: SLAMetric): Promise<void> {
    const { tenantId, metricName, currentValue, targetValue } = metric;
    
    const stats = await this.getOrCreateStats(tenantId);
    
    const updates: any = {
      updated_at: new Date()
    };

    if (metricName === 'TASK_SUCCESS_RATE') {
      updates.total_requests = (stats.total_requests || 0) + 1;
      if (currentValue < (targetValue || 0.85)) { // 默认 85% 成功率
        updates.failed_requests = (stats.failed_requests || 0) + 1;
      }
    } else if (metricName === 'API_LATENCY') {
      updates.p95_latency_ms = currentValue;
    }

    await db(this.TABLE_NAME).where({ tenant_id: tenantId }).update(updates);

    // 联动熔断逻辑 (针对核心成功率)
    if (metricName === 'TASK_SUCCESS_RATE') {
      await this.checkCircuitBreaker(tenantId, updates.total_requests || stats.total_requests, updates.failed_requests || stats.failed_requests);
    }
  }

  /**
   * 熔断检查
   */
  private static async checkCircuitBreaker(tenantId: string, total: number, failed: number): Promise<void> {
    if (total < 100) return; 

    const failureRate = failed / total;
    const threshold = 0.15; // 15% 失败率熔断

    if (failureRate > threshold) {
      logger.error(`[SLA] Circuit breaker triggered for Tenant: ${tenantId} (Failure Rate: ${(failureRate * 100).toFixed(2)}%)`);
      
      await db('cf_tenants').where({ id: tenantId }).update({
        status: 'SUSPENDED',
        updated_at: new Date()
      });

      await WebhookService.trigger({
        tenantId,
        eventType: 'TASK_FAILED',
        payload: {
          type: 'SLA_CIRCUIT_BREAKER',
          reason: `High failure rate: ${(failureRate * 100).toFixed(2)}%`,
          action: 'TENANT_SUSPENDED'
        },
        traceId: `sla-${Date.now()}`,
        timestamp: Date.now()
      });
    }
  }

  private static async getOrCreateStats(tenantId: string) {
    let stats = await db(this.TABLE_NAME).where({ tenant_id: tenantId }).first();
    if (!stats) {
      await db(this.TABLE_NAME).insert({
        tenant_id: tenantId,
        total_requests: 0,
        failed_requests: 0,
        p95_latency_ms: 0,
        created_at: new Date(),
        updated_at: new Date()
      });
      stats = { total_requests: 0, failed_requests: 0, p95_latency_ms: 0 };
    }
    return stats;
  }

  /**
   * 初始化表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.TABLE_NAME);
    if (!exists) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('tenant_id', 64).primary();
        table.integer('total_requests').defaultTo(0);
        table.integer('failed_requests').defaultTo(0);
        table.float('p95_latency_ms').defaultTo(0);
        table.timestamps(true, true);
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * 获取租户 SLA 达成率报告
   */
  static async getSLAReport(tenantId: string) {
    const stats = await db(this.TABLE_NAME).where({ tenant_id: tenantId }).first();
    if (!stats) return [];

    return [
      {
        metric: 'TASK_SUCCESS_RATE',
        attainmentRate: stats.total_requests > 0 ? ((stats.total_requests - stats.failed_requests) / stats.total_requests) * 100 : 100
      },
      {
        metric: 'API_LATENCY',
        currentValue: stats.p95_latency_ms
      }
    ];
  }
}
