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

export interface ApiChangeRecord {
  endpoint: string;
  method: string;
  version: string;
  changes: {
    field: string;
    type: 'ADDED' | 'REMOVED' | 'MODIFIED' | 'DEPRECATED';
    description: string;
    isBreaking: boolean;
  }[];
}

/**
 * [BIZ_KER_119] API 版本迁移风险评估器 (Migration)
 * @description 核心逻辑：分析 API 定义的变更历史，识别潜在的不兼容变更（Breaking Changes）。
 * 针对前端 Console 或第三方集成方生成版本迁移风险报告。
 * 遵循 Autocomplete-First (V31.5) 规范，提供详尽的 JSDoc。
 */
export class V2MigrationAdvisor {
  /**
   * 评估 API 变更风险
   * @param oldSchema 旧版本 API 定义
   * @param newSchema 新版本 API 定义
   * @returns 风险评估结果，包含风险等级与迁移建议
   */
  static async evaluateMigrationRisk(oldSchema: ApiChangeRecord, newSchema: ApiChangeRecord): Promise<any> {
    logger.info(`[MigrationAdvisor] Evaluating risk for ${newSchema.endpoint} ${newSchema.version}`);

    const breakingChanges = newSchema.changes.filter(c => c.isBreaking);
    const riskLevel = breakingChanges.length > 0 ? 'HIGH' : (newSchema.changes.length > 0 ? 'MEDIUM' : 'LOW');

    const report = this.generateMarkdownReport(newSchema, breakingChanges, riskLevel);
    await SemanticLogService.logSemantic(report, riskLevel === 'HIGH' ? 'ERROR' : 'INFO', 'API_MIGRATION');

    return {
      endpoint: newSchema.endpoint,
      version: newSchema.version,
      riskLevel,
      breakingChangesCount: breakingChanges.length,
      recommendation: riskLevel === 'HIGH' ? '需立即通知前端团队进行逻辑适配，严禁直接上线。' : '可平滑迁移，建议在灰度环境下验证。'
    };
  }

  /**
   * 生成 Markdown 格式的迁移报告
   * @private
   */
  private static generateMarkdownReport(schema: ApiChangeRecord, breaking: any[], risk: string): string {
    let md = `### 🚀 API Migration Risk Report: \`${schema.endpoint}\` (${schema.version})\n\n`;
    md += `**Overall Risk Level:** ${risk}\n\n`;

    if (breaking.length > 0) {
      md += `**🚨 Breaking Changes Detected:**\n`;
      breaking.forEach(c => {
        md += `- \`[${c.type}]\` Field: \`${c.field}\` - ${c.description}\n`;
      });
    } else {
      md += `**✅ No breaking changes detected.**\n`;
    }

    md += `\n**Full Change Log:**\n`;
    schema.changes.forEach(c => {
      md += `- \`${c.field}\`: ${c.description} (${c.type})\n`;
    });

    return md;
  }
}
