import * as crypto from 'crypto';
import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';

/**
 * [CORE_SEC_13] 基于差分隐私 (Differential Privacy) 的多维报表分析
 * @description 核心逻辑：在保护单租户隐私前提下共享全局趋势。通过向统计聚合结果中注入拉普拉斯噪声 (Laplace Noise)，
 * 确保即使攻击者拥有外部辅助信息，也无法推断出单个租户的具体数据，满足 $\epsilon$-差分隐私定义。
 */
export class DifferentialPrivacyService {
  /**
   * 为聚合指标添加噪声 (Laplace Mechanism)
   */
  static async anonymizeMetric(value: number, sensitivity: number, epsilon: number = 0.1): Promise<number> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('CORE_SEC_DIFF_PRIVACY'))) {
      logger.warn('[DiffPrivacy] Service disabled, returning original value.');
      return value;
    }

    // 1. 生成拉普拉斯噪声: Noise ~ Lap(sensitivity / epsilon)
    const scale = sensitivity / epsilon;
    const noise = this.generateLaplaceNoise(scale);
    
    logger.debug(`[DiffPrivacy] Adding noise: ${noise.toFixed(4)} to value: ${value}`);
    return value + noise;
  }

  /**
   * 生成拉普拉斯噪声
   */
  private static generateLaplaceNoise(scale: number): number {
    const u = Math.random() - 0.5;
    return -scale * Math.sign(u) * Math.log(1 - 2 * Math.abs(u));
  }

  /**
   * 匿名化全局趋势报表 (Batch Processing)
   */
  static async anonymizeReport(report: Record<string, number>, config: { sensitivity: number; epsilon: number }): Promise<Record<string, number>> {
    const result: Record<string, number> = {};
    for (const [key, val] of Object.entries(report)) {
      result[key] = await this.anonymizeMetric(val, config.sensitivity, config.epsilon);
    }
    return result;
  }
}
