// SECURITY FIX: Rank 5A - Basic Prompt Injection Pattern Blocking
// Sanitizes user input to detect and block common prompt injection attacks

/**
 * Result of input sanitization
 */
export interface SanitizationResult {
  /** Original input (use this if not blocked) */
  original: unknown
  /** Sanitized input text (with attack patterns redacted) */
  sanitized: string
  /** List of detected attack pattern types */
  warnings: string[]
  /** Whether input is blocked (3+ distinct attack types) */
  blocked: boolean
}

/**
 * Sanitize user input to detect and block prompt injection attacks
 *
 * Basic pattern blocking for common attack vectors:
 * 1. System prompt extraction attempts
 * 2. Role manipulation attempts
 * 3. Delimiter injection (fake system sections)
 * 4. Tool/function injection attempts
 *
 * Blocking threshold: 3+ distinct warning types indicates sophisticated attack
 *
 * @param input - User input (any format)
 * @returns Sanitization result with warnings, sanitized text, and blocked status
 */
export function sanitizeUserInput(input: unknown): SanitizationResult {
  let text: string

  // Extract text from input (string or {message: "..."} format)
  if (typeof input === 'string') {
    text = input
  } else if (input && typeof input === 'object' && 'message' in input) {
    text = String((input as Record<string, unknown>).message)
  } else if (input === null || input === undefined) {
    text = ''
  } else {
    text = JSON.stringify(input)
  }

  const warnings: string[] = []
  let sanitized = text

  // Pattern 1: System prompt extraction attempts
  const systemPromptPatterns = [
    /ignore\s+(all\s+)?instructions?/i,
    /ignore\s+(all\s+)?(previous|prior|above)/i,
    /disregard\s+(all\s+)?(previous|system)\s+instructions?/i,
    /print\s+(your\s+)?(system\s+)?prompt/i,
    /(show|tell)\s+(me\s+)?your\s+(system\s+)?prompt/i,
    /what\s+(are|is)\s+your\s+(system\s+)?instructions?/i,
    /show\s+(me\s+)?your\s+configuration/i,
    /repeat\s+everything\s+before/i
  ]

  for (const pattern of systemPromptPatterns) {
    if (pattern.test(text)) {
      warnings.push('system_prompt_extraction')
      sanitized = sanitized.replace(pattern, '[REDACTED: system prompt extraction attempt]')
      break
    }
  }

  // Pattern 2: Role manipulation attempts
  const rolePatterns = [
    /you\s+are\s+now\s+(a|an|the)/i,
    /act\s+as\s+(a|an|the)/i,
    /pretend\s+(you\s+are|to\s+be)/i,
    /from\s+now\s+on,?\s+you/i,
    /forget\s+your\s+(previous\s+)?role/i,
    /jailbreak/i
  ]

  for (const pattern of rolePatterns) {
    if (pattern.test(text)) {
      warnings.push('role_manipulation')
      sanitized = sanitized.replace(pattern, '[REDACTED: role manipulation attempt]')
      break
    }
  }

  // Pattern 3: Delimiter injection (fake system sections)
  const delimiterPatterns = [
    /^\s*={3,}/m,           // === at line start (with optional whitespace)
    /^\s*-{3,}/m,           // --- at line start (with optional whitespace)
    /^\s*#{2,}\s*SYSTEM/mi, // ## SYSTEM headers (with optional whitespace)
    /<\|?system\|?>/i       // <system> or <|system|> tags
  ]

  for (const pattern of delimiterPatterns) {
    if (pattern.test(text)) {
      warnings.push('delimiter_injection')
      sanitized = sanitized.replace(pattern, '[REDACTED: delimiter injection]')
      break
    }
  }

  // Pattern 4: Tool/function injection attempts
  const toolPatterns = [
    /<function[>\s]/i,
    /<tool[>\s]/i,
    /"type":\s*"tool_call"/i
  ]

  for (const pattern of toolPatterns) {
    if (pattern.test(text)) {
      warnings.push('tool_injection')
      sanitized = sanitized.replace(pattern, '[REDACTED: tool injection attempt]')
      break
    }
  }

  // Decision: Block if 3+ distinct warning types detected
  // (This indicates a sophisticated, multi-vector attack)
  const uniqueWarnings = [...new Set(warnings)]
  const blocked = uniqueWarnings.length >= 3

  return {
    original: input,
    sanitized,
    warnings: uniqueWarnings,
    blocked
  }
}
