import { logger } from '../../utils/logger';
import { PricingService, ProfitSnapshot } from '../../services/PricingService';

export interface GuardrailCheckResult {
  passed: boolean;
  violations: string[];
  severity: 'BLOCK' | 'WARN' | 'PASS';
}

/**
 * [CORE_GOV_04] AI 高风险盲区兜底治理 (Blind-Spot Guardrail)
 * @description 对 AI 生成的结果、关键业务指标进行最后的自动化兜底校验
 */
export class GuardrailService {
  /**
   * 业务指标口径校验 (防止分析口径漂移)
   */
  static validateProfitLogic(snapshot: ProfitSnapshot): GuardrailCheckResult {
    const violations: string[] = [];
    
    // 校验 1：净利计算公式闭环 (售价 - 成本 - 各项费用 = 净利)
    const calculatedNet = snapshot.sellingPrice 
      - snapshot.purchasePrice 
      - snapshot.platformFee 
      - snapshot.logisticsCost 
      - snapshot.tax 
      - snapshot.fxHedging 
      - snapshot.afterSalesLoss 
      - snapshot.adAmortization;

    if (Math.abs(calculatedNet - snapshot.netProfit) > 0.01) {
      violations.push(`Profit calculation drift: expected ${calculatedNet.toFixed(2)}, got ${snapshot.netProfit}`);
    }

    // 校验 2：ROI 与 净利的一致性
    const costBasis = snapshot.purchasePrice + snapshot.logisticsCost;
    const expectedROI = costBasis > 0 ? snapshot.netProfit / costBasis : 0;
    if (Math.abs(expectedROI - snapshot.roi) > 0.001) {
      violations.push(`ROI consistency error: expected ${expectedROI.toFixed(4)}, got ${snapshot.roi}`);
    }

    return {
      passed: violations.length === 0,
      violations,
      severity: violations.length > 0 ? 'BLOCK' : 'PASS'
    };
  }

  /**
   * 异常链路兜底校验
   */
  static async validateTaskConsistency(taskId: string): Promise<GuardrailCheckResult> {
    logger.info(`[Guardrail] Checking task consistency for ${taskId}`);
    // 实际应检查任务在数据库中的 traceId 完整性、状态机流转记录、审计日志是否存在
    return { passed: true, violations: [], severity: 'PASS' };
  }

  /**
   * 凭据安全暴露扫描
   */
  static scanForSensitiveLeaks(data: any): string[] {
    const sensitivePatterns = [
      /password/i, /token/i, /secret/i, /sk-[a-zA-Z0-9]{32,}/ // 匹配 OpenAI Key 等
    ];
    
    const leaks: string[] = [];
    const check = (val: any, path: string = '') => {
      if (typeof val === 'string') {
        if (sensitivePatterns.some(p => p.test(val))) leaks.push(`Leak detected in ${path}`);
      } else if (typeof val === 'object' && val !== null) {
        Object.keys(val).forEach(k => check(val[k], `${path}.${k}`));
      }
    };

    check(data);
    return leaks;
  }
}
