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

export interface NetworkMetric {
  sourceNodeId: string;
  targetNodeId: string;
  latencyMs: number;
  jitterMs: number;
  hopCount: number;
  packetLossRate: number; // 0-1
  status: 'OPTIMAL' | 'DEGRADED' | 'DISCONNECTED';
  timestamp: Date;
}

/**
 * [CORE_TELE_TOPO] 全球节点实时拓扑遥测 (Network Topology)
 * @description 核心逻辑：采集 Hub 节点间 P2P 通信的实时质量指标。
 * 为 AGI 提供网络层的“数字孪生”视图，支持自动识别高延迟链路并触发路由重排。
 */
export class NetworkTopologyService {
  private static readonly TOPO_TABLE = 'cf_network_topology_metrics';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TOPO_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TOPO_TABLE} table...`);
      await db.schema.createTable(this.TOPO_TABLE, (table) => {
        table.increments('id').primary();
        table.string('source_node_id', 64).notNullable();
        table.string('target_node_id', 64).notNullable();
        table.float('latency_ms');
        table.float('jitter_ms');
        table.integer('hop_count');
        table.float('packet_loss_rate');
        table.string('status', 16);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['source_node_id', 'target_node_id', 'created_at']);
      });
      logger.info(`✅ Table ${this.TOPO_TABLE} created`);
    }
  }

  /**
   * 记录节点间通信指标 (Telemetry Collection)
   */
  static async recordMetric(metric: NetworkMetric) {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('CORE_TELE_NETWORK_TOPO', 'SYSTEM'))) {
      return;
    }

    try {
      // 1. 状态自动评级逻辑
      let status: NetworkMetric['status'] = 'OPTIMAL';
      if (metric.latencyMs > 500 || metric.packetLossRate > 0.05) {
        status = 'DEGRADED';
      }
      if (metric.packetLossRate > 0.5) {
        status = 'DISCONNECTED';
      }

      // 2. 持久化至数据库 (Zero-Mock Policy)
      await db(this.TOPO_TABLE).insert({
        source_node_id: metric.sourceNodeId,
        target_node_id: metric.targetNodeId,
        latency_ms: metric.latencyMs,
        jitter_ms: metric.jitterMs,
        hop_count: metric.hopCount,
        packet_loss_rate: metric.packetLossRate,
        status: status,
        created_at: metric.timestamp || new Date()
      });

      logger.info(`[NetworkTopo] Recorded metric from ${metric.sourceNodeId} to ${metric.targetNodeId}: ${metric.latencyMs}ms`);
    } catch (err: any) {
      logger.error(`[NetworkTopo] Failed to record metric: ${err.message}`);
    }
  }

  /**
   * 获取最新的全球网络拓扑快照 (用于可视化)
   */
  static async getTopologySnapshot() {
    // 聚合获取每个链路最新的指标
    return db(this.TOPO_TABLE)
      .select('source_node_id', 'target_node_id', 'latency_ms', 'status', 'created_at')
      .whereIn(['source_node_id', 'target_node_id', 'created_at'], function() {
        this.select('source_node_id', 'target_node_id', db.raw('MAX(created_at)'))
          .from(NetworkTopologyService.TOPO_TABLE)
          .groupBy('source_node_id', 'target_node_id');
      });
  }

  /**
   * 识别网络瓶颈 (AGI Insight)
   */
  static async detectBottlenecks() {
    const degradedLinks = await db(this.TOPO_TABLE)
      .where('status', '!=', 'OPTIMAL')
      .andWhere('created_at', '>', new Date(Date.now() - 3600000)) // 最近 1 小时
      .orderBy('latency_ms', 'desc');

    return degradedLinks;
  }
}
