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

/**
 * [BIZ_KER_121] 静态资源缓存一致性校验 (Cache Sync)
 * @description 核心逻辑：定期对比源站与 CDN 节点的静态资源（JS/CSS/Images）哈希值。
 * 识别因 CDN 刷新延迟或运营商劫持导致的“脏缓存”问题。
 * 联动语义日志中心输出一致性报告，并对不匹配资源进行预警。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class CacheConsistencyService {
  private static readonly RESOURCE_LIST = [
    '/static/js/main.js',
    '/static/css/theme.css'
  ];
  private static readonly CDN_ENDPOINTS = [
    'https://cdn1.crawlful.com',
    'https://cdn2.crawlful.com'
  ];

  /**
   * 初始化缓存校验任务
   */
  static async init() {
    logger.info(`[CacheConsistency] Initializing CDN cache sync monitor...`);
    this.runCheck();
    setInterval(() => this.runCheck(), 3600000); // 每小时校验一次
  }

  /**
   * 执行一致性校验
   * @private
   */
  private static async runCheck() {
    const report: string[] = [];
    let hasIssue = false;

    for (const resource of this.RESOURCE_LIST) {
      try {
        // 1. 获取源站哈希 (模拟从本地文件读取或 Origin 请求)
        const originHash = await this.getResourceHash(`https://origin.crawlful.com${resource}`);
        
        // 2. 对比各 CDN 节点
        for (const cdn of this.CDN_ENDPOINTS) {
          const cdnHash = await this.getResourceHash(`${cdn}${resource}`);
          
          if (originHash !== cdnHash) {
            hasIssue = true;
            report.push(`❌ Mismatch: \`${resource}\` on \`${cdn}\` (Expected: ${originHash.substring(0, 8)}, Got: ${cdnHash.substring(0, 8)})`);
          } else {
            report.push(`✅ Match: \`${resource}\` on \`${cdn}\``);
          }
        }
      } catch (err: any) {
        logger.error(`[CacheConsistency] Failed to check ${resource}: ${err.message}`);
      }
    }

    const mdReport = this.generateMarkdownReport(report, hasIssue);
    await SemanticLogService.logSemantic(mdReport, hasIssue ? 'ERROR' : 'INFO', 'CACHE_AUDIT');
  }

  /**
   * 获取远程资源的 MD5 哈希
   * @private
   */
  private static async getResourceHash(url: string): Promise<string> {
    try {
      const response = await axios.get(url, { responseType: 'arraybuffer', timeout: 5000 });
      return crypto.createHash('md5').update(Buffer.from(response.data)).digest('hex');
    } catch (err) {
      return 'FETCH_FAILED';
    }
  }

  /**
   * 生成 Markdown 报告
   * @private
   */
  private static generateMarkdownReport(results: string[], hasIssue: boolean): string {
    return `### 🌐 CDN Cache Consistency Audit\n\n` +
           `**Status:** ${hasIssue ? '🚨 Issues Detected' : '✅ All Synchronized'}\n\n` +
           `**Audit Details:**\n` +
           results.map(r => `- ${r}`).join('\n') +
           (hasIssue ? `\n\n**Recommendation:** 请立即执行 CDN 全量刷新，或核查源站发布流水线是否同步完成。` : '');
  }
}
