import { DomainRegistry } from '../runtime/DomainRegistry';
import { logger } from '../../utils/logger';
import { SemanticLogService } from '../telemetry/SemanticLogService';

/**
 * [BIZ_INF_110] 服务拓扑依赖自检 (Health Mesh)
 * @description 核心逻辑：扫描已注册的领域服务，识别各模块间的依赖拓扑。
 * 通过拓扑排序与环形检测算法识别是否存在循环引用 (Circular Reference)。
 * 联动语义日志中心输出拓扑结构报告并对循环依赖进行预警。
 */
export class DependencyGraphService {
  private static readonly MAX_DEPTH = 10; // 拓扑扫描深度限制

  /**
   * 初始化拓扑扫描
   */
  static async init() {
    this.runCheck();
    logger.info(`[HealthMesh] Dependency graph service initialized`);
  }

  /**
   * 执行依赖检查
   */
  private static async runCheck() {
    try {
      const domains = DomainRegistry.getDomains();
      const dependencyMap: Map<string, string[]> = new Map();

      for (const domain of domains) {
        dependencyMap.set(domain.name, this.extractDependencies(domain));
      }

      const circularReferences = this.findCircularReferences(dependencyMap);

      const report = await this.generateReport(dependencyMap, circularReferences);
      await SemanticLogService.logSemantic(report, 'INFO', 'HEALTH_MESH');
      logger.info(`[HealthMesh] Dependency graph report generated`);
    } catch (err: any) {
      logger.error(`[HealthMesh] Scan failed: ${err.message}`);
    }
  }

  /**
   * 提取领域服务的依赖
   * (模拟逻辑：通过静态分析或依赖注入列表提取依赖关系)
   */
  private static extractDependencies(domain: any): string[] {
    // 实际应通过扫描类属性或构造函数参数提取依赖关系
    // 此处使用模拟数据以便演示拓扑分析能力
    const dependencies: string[] = [];
    if (domain.name === 'SlowQueryAdvisor') dependencies.push('SemanticLogService');
    if (domain.name === 'CertsMonitorService') dependencies.push('LogMaskingService', 'SemanticLogService');
    if (domain.name === 'IndexCoverageService') dependencies.push('SemanticLogService');
    return dependencies;
  }

  /**
   * 拓扑环形检测 (Tarjan 或 DFS 路径检测)
   */
  private static findCircularReferences(dependencyMap: Map<string, string[]>): string[][] {
    const circulars: string[][] = [];
    const visited: Set<string> = new Set();
    const stack: string[] = [];

    const dfs = (current: string) => {
      if (stack.includes(current)) {
        const cycle = stack.slice(stack.indexOf(current));
        cycle.push(current);
        circulars.push(cycle);
        return;
      }

      if (visited.has(current)) return;

      visited.add(current);
      stack.push(current);

      const deps = dependencyMap.get(current) || [];
      for (const dep of deps) {
        dfs(dep);
      }

      stack.pop();
    };

    for (const domainName of dependencyMap.keys()) {
      dfs(domainName);
    }

    return circulars;
  }

  /**
   * 生成拓扑分析报告
   */
  private static async generateReport(dependencyMap: Map<string, string[]>, circulars: string[][]): Promise<string> {
    let report = `### 🕸️ Service Topology Dependency Audit (Health Mesh)\n\n`;
    report += `**Total Services Monitored:** ${dependencyMap.size}\n\n`;

    if (circulars.length > 0) {
      report += `**🚨 FATAL: Circular References Detected!**\n`;
      circulars.forEach(cycle => {
        report += `- \`${cycle.join(' -> ')}\` (请立即重构，解耦循环依赖以防止启动失败或内存泄漏)\n`;
      });
    } else {
      report += `**✅ All services follow a clean DAG (Directed Acyclic Graph).**\n`;
    }

    report += `\n**Dependency Map Snapshot:**\n`;
    for (const [service, deps] of dependencyMap.entries()) {
      if (deps.length > 0) {
        report += `- \`${service}\` depends on: \`${deps.join(', ')}\`\n`;
      }
    }

    return report;
  }
}
