import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';
import { AIService } from '../../services/AIService';
import { TracingTopoService, TracingTopo } from './TracingTopoService';

export interface DiagnosticReport {
  id?: number;
  tenantId?: string;
  issueType: 'LATENCY_SPIKE' | 'ERROR_RATE_HIGH' | 'RESOURCE_EXHAUSTION';
  rootCause: string;
  affectedNodes: string[];
  recommendation: string;
  severity: 'MEDIUM' | 'HIGH' | 'CRITICAL';
  status: 'OPEN' | 'RESOLVED';
  created_at?: Date;
}

/**
 * [CORE_TELE_10] 系统级瓶颈 AI 自动诊断报告 (Auto-Diagnostics)
 * @description 核心逻辑：联动 [TracingTopoService] 获取实时拓扑与指标，利用 AGI (GPT-4o) 
 * 自动分析系统级性能瓶颈、死锁或突发异常。生成包含根因分析 (RCA) 与自动修复建议的诊断报告。
 */
export class AutoDiagnosticsService {
  private static readonly REPORT_TABLE = 'cf_system_diagnostics';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.REPORT_TABLE);
    if (!hasTable) {
      logger.info('📦 Creating cf_system_diagnostics table...');
      await db.schema.createTable(this.REPORT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('issue_type', 32).notNullable();
        table.text('root_cause').notNullable();
        table.json('affected_nodes');
        table.text('recommendation');
        table.string('severity', 16);
        table.string('status', 16).defaultTo('OPEN');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 运行自动诊断流程 (CORE_TELE_10)
   */
  static async runDiagnostics(tenantId: string) {
    if (!(await FeatureGovernanceService.isEnabled('CORE_TELE_AUTO_DIAGNOSTICS', tenantId))) {
      return { status: 'DISABLED' };
    }

    logger.info(`[AutoDiagnostics] Running system-wide check for Tenant: ${tenantId}`);

    try {
      // 1. 获取分布式拓扑结构与指标
      const topo: TracingTopo = await TracingTopoService.getLiveTopo(tenantId);
      
      // 2. 调用 AGI 进行深度诊断 (Root Cause Analysis)
      const diagnosis = await AIService.performSystemDiagnostics({
        topo,
        tenantId
      });

      // 3. 存储诊断报告
      const [id] = await db(this.REPORT_TABLE).insert({
        tenant_id: tenantId,
        issue_type: diagnosis.issueType,
        root_cause: diagnosis.rootCause,
        affected_nodes: JSON.stringify(diagnosis.affectedNodes),
        recommendation: diagnosis.recommendation,
        severity: diagnosis.severity,
        status: 'OPEN',
        created_at: new Date()
      });

      // 4. 高危异常告警
      if (diagnosis.severity === 'CRITICAL' || diagnosis.severity === 'HIGH') {
        logger.error(`[AutoDiagnostics] CRITICAL SYSTEM ISSUE detected for Tenant ${tenantId}! RCA: ${diagnosis.rootCause}`);
        // TODO: 集成 Webhook/SMS 告警
      }

      return { status: 'COMPLETED', reportId: id, diagnosis };
    } catch (err: any) {
      logger.error(`[AutoDiagnostics] Diagnostics failed: ${err.message}`);
      throw err;
    }
  }

  /**
   * 获取最近的诊断报告
   */
  static async getRecentReports(limit: number = 5) {
    return await db(this.REPORT_TABLE)
      .orderBy('created_at', 'desc')
      .limit(limit);
  }
}
