/**
 * Scrubs credential patterns from plain-text memory facts at write time.
 * Patterns: OpenAI keys (sk-), GitHub PATs (ghp_), Google API keys (AIza),
 * JWT-shaped tokens, and key=value pairs with sensitive key names.
 */

/** Matches well-known credential token shapes inline in text. */
const CREDENTIAL_INLINE_RE =
  /\b(sk-[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{36,}|AIza[0-9A-Za-z_-]{35,}|[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{20,})/g;

/** Matches key=value or key: value patterns with sensitive key names. */
const SENSITIVE_KEY_VALUE_RE =
  /(?:api[_-]?key|token|secret|password|bearer|auth)\s*[:=]\s*\S+/gi;

/**
 * Returns the fact with credential-shaped values replaced by [REDACTED].
 * Safe facts (no credentials) are returned unchanged.
 */
export function sanitizeMemoryFact(raw: string): string {
  // First apply the key=value pattern (may match before inline creds)
  let result = raw.replace(SENSITIVE_KEY_VALUE_RE, "[REDACTED]");
  // Then apply the inline credential pattern
  result = result.replace(CREDENTIAL_INLINE_RE, "[REDACTED]");
  return result;
}
