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

export interface GovernanceRule {
  id: string;
  name: string;
  category: 'READABILITY' | 'SAFETY' | 'BUSINESS_LOGIC';
  severity: 'BLOCK' | 'WARN';
  check: (content: any) => { passed: boolean; message?: string };
}

/**
 * [CORE_GOV_02] AI-First 代码与逻辑治理规范
 * @description 建立业务 Service 准入校验与逻辑安全红线检测，防止 AI 生成代码引入业务风险
 */
export class AIGovernanceService {
  private static readonly RULES: GovernanceRule[] = [
    {
      id: 'R1',
      name: 'Trace Context Mandatory',
      category: 'SAFETY',
      severity: 'BLOCK',
      check: (data) => ({
        passed: !!data.traceId && !!data.tenantId,
        message: 'Missing mandatory trace context: traceId or tenantId'
      })
    },
    {
      id: 'R2',
      name: 'Sensitive Data Masking',
      category: 'SAFETY',
      severity: 'BLOCK',
      check: (data) => {
        const sensitivePatterns = [/password/i, /secret/i, /token/i, /apikey/i, /sk-/i];
        const keys = Object.keys(data);
        const leaks = keys.filter(k => sensitivePatterns.some(p => p.test(k)));
        
        // 同时检查值中是否包含 sk- 等特征
        const valueLeaks = Object.values(data).filter(v => typeof v === 'string' && /sk-[a-zA-Z0-9]{20,}/.test(v));

        return {
          passed: leaks.length === 0 && valueLeaks.length === 0,
          message: `Potential sensitive data exposure detected in keys (${leaks.join(', ')}) or values.`
        };
      }
    },
    {
      id: 'R3',
      name: 'Business Logic Consistency',
      category: 'BUSINESS_LOGIC',
      severity: 'WARN',
      check: (data) => {
        if (data.netProfit && data.sellingPrice && data.purchasePrice) {
          const expected = data.sellingPrice - data.purchasePrice;
          return {
            passed: data.netProfit <= expected,
            message: 'Net profit exceeds gross margin (sellingPrice - purchasePrice)'
          };
        }
        return { passed: true };
      }
    }
  ];

  /**
   * 对 AI 生成的逻辑数据进行准入校验
   */
  static validate(data: any): { passed: boolean; violations: string[] } {
    logger.info('[AIGovernance] Running safety checks on AI-generated data...');
    
    const violations: string[] = [];
    for (const rule of this.RULES) {
      const result = rule.check(data);
      if (!result.passed) {
        violations.push(`[${rule.severity}] ${rule.name}: ${result.message}`);
      }
    }

    return {
      passed: !violations.some(v => v.includes('[BLOCK]')),
      violations
    };
  }

  /**
   * 生成 AI 开发规范摘要 (DOD 检查单)
   */
  static getStandardsSummary(): string[] {
    return [
      '所有 Service 必须支持 traceContext 透传。',
      '敏感凭据必须收敛至 VaultService，严禁明文打印日志。',
      '状态变更必须通过 TaskFSM，严禁绕过状态机。',
      '多租户隔离字段 (tenantId/shopId) 必须在每个 DB 操作中作为强制过滤项。'
    ];
  }
}
