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

export interface PromptScanResult {
  isSafe: boolean;
  detectedThreats: string[];
  sanitizedPrompt: string;
  riskScore: number; // 0-1
}

/**
 * [CORE_SEC_12] 针对 LLM 注入的指令安全过滤层 (Prompt Guard)
 * @description 核心逻辑：拦截恶意的 Prompt 注入攻击（如：“忽略之前的所有指令”）。
 * 采用基于正则表达式的启发式检测与语义意图分析双重防御。
 */
export class PromptGuardService {
  private static readonly BLACKLIST_PATTERNS = [
    /ignore (all )?previous/i,
    /system (prompt|message|instruction)/i,
    /you are now (a|an) (.*)/i,
    /bypass/i,
    /jailbreak/i,
    /do anything now/i,
    /reveal (your )?instruction/i
  ];

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable('cf_prompt_attacks');
    if (!hasTable) {
      console.log('📦 Creating cf_prompt_attacks table...');
      await db.schema.createTable('cf_prompt_attacks', (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.text('prompt');
        table.string('prompt_hash', 64);
        table.float('risk_score');
        table.json('detected_threats');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'prompt_hash']);
      });
      console.log('✅ Table cf_prompt_attacks created');
    }
  }

  /**
   * 扫描并清洗 Prompt
   */
  static async scanPrompt(prompt: string, tenantId?: string): Promise<PromptScanResult> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('CORE_SEC_PROMPT_GUARD', tenantId))) {
      return { isSafe: true, detectedThreats: [], sanitizedPrompt: prompt, riskScore: 0 };
    }

    logger.info(`[PromptGuard] Scanning prompt for Tenant: ${tenantId}`);

    const detectedThreats: string[] = [];
    let riskScore = 0;

    // 1. 启发式黑名单匹配
    for (const pattern of this.BLACKLIST_PATTERNS) {
      if (pattern.test(prompt)) {
        detectedThreats.push(`Pattern match: ${pattern.toString()}`);
        riskScore += 0.3;
      }
    }

    // 2. 模拟语义意图分析 (实际场景可调用更轻量的模型进行二分类)
    if (prompt.length > 500 && prompt.includes('---')) {
       detectedThreats.push('Suspicious delimiter injection attempt');
       riskScore += 0.2;
    }

    const isSafe = riskScore < 0.6;
    
    // 3. 执行基础清洗 (Sanitization)
    let sanitizedPrompt = prompt;
    if (!isSafe) {
      sanitizedPrompt = "[REDACTED BY PROMPT GUARD DUE TO SECURITY RISK]";
      logger.warn(`[PromptGuard] Blocked malicious prompt from Tenant ${tenantId}`);
    }

    return {
      isSafe,
      detectedThreats,
      sanitizedPrompt,
      riskScore: Math.min(1.0, riskScore)
    };
  }

  /**
   * 记录注入攻击事件用于审计
   */
  static async logAttack(tenantId: string, prompt: string, result: PromptScanResult) {
    const hash = crypto.createHash('sha256').update(prompt).digest('hex');
    logger.error(`[PromptGuard] Attack detected! Tenant: ${tenantId}, Hash: ${hash}, Score: ${result.riskScore}`);
    
    try {
      await db('cf_prompt_attacks').insert({
        tenant_id: tenantId,
        prompt: prompt,
        prompt_hash: hash,
        risk_score: result.riskScore,
        detected_threats: JSON.stringify(result.detectedThreats)
      });
    } catch (err: any) {
      logger.error(`[PromptGuard] Failed to log attack to DB: ${err.message}`);
    }
  }
}
