# Categorize errors for better grouping and alerting
msg = string!(.message)

if .level == "error" || .level == "fatal" {
  if match(msg, r'(?i)(timeout|timed out|deadline exceeded|context deadline)') {
    .error_category = "timeout"
  }
  if .error_category == null && match(msg, r'(?i)(connection refused|connection reset|network|unreachable|dns|ECONNREFUSED|ETIMEDOUT|ENOTFOUND)') {
    .error_category = "network"
  }
  if .error_category == null && match(msg, r'(?i)(out of memory|oom|memory limit|heap|MemoryError|ENOMEM)') {
    .error_category = "memory"
  }
  if .error_category == null && match(msg, r'(?i)(permission denied|forbidden|unauthorized|auth|401|403|AccessDenied)') {
    .error_category = "auth"
  }
  if .error_category == null && match(msg, r'(?i)(not found|404|missing|no such|FileNotFoundError|ENOENT)') {
    .error_category = "not_found"
  }
  if .error_category == null && match(msg, r'(?i)(crash|panic|segfault|sigsegv|core dump|SIGSEGV)') {
    .error_category = "crash"
  }
  if .error_category == null && match(msg, r'(?i)(validation|invalid|malformed|parse error|ValueError|TypeError|SyntaxError)') {
    .error_category = "validation"
  }
  if .error_category == null && match(msg, r'(?i)(database|sql|postgres|mysql|mongo|redis|connection pool)') {
    .error_category = "database"
  }
  if .error_category == null && match(msg, r'(?i)(rate limit|throttle|too many requests|429)') {
    .error_category = "rate_limit"
  }
  if .error_category == null && match(msg, r'(?i)(ssl|tls|certificate|handshake)') {
    .error_category = "ssl"
  }
  if .error_category == null {
    .error_category = "other"
  }
}

if .error_type != null && match(string!(.error_type), r'(?:Error|Exception)$') {
  .is_python_exception = true
}
