/**
 * Intent Detector Utility
 * Detects the INTENT of code patterns, not just keywords
 *
 * This addresses false positives where:
 * - setState() is flagged as a redirect (it's React state, not navigation)
 * - Error codes like 'SAME_PASSWORD' are flagged as password exposure
 * - Signed URLs are flagged as token exposure
 * - React Hook Form's shouldValidate: false is flagged as bypass
 */

// ============================================================================
// Redirect vs State Setter Detection
// ============================================================================

/**
 * React state setter patterns - these are NOT redirects
 */
const REACT_STATE_SETTER_PATTERNS = [
  // useState setters: setFoo(value)
  /\bset[A-Z][a-zA-Z]*\s*\(/,
  // Zustand/state manager: store.setFoo()
  /\.\s*set[A-Z][a-zA-Z]*\s*\(/,
  // Redux dispatch pattern
  /dispatch\s*\(/,
  // Recoil/Jotai
  /\buseSetRecoilState\b/,
  /\bsetAtom\b/,
]

/**
 * Actual redirect/navigation patterns
 */
const REDIRECT_PATTERNS = [
  // Framework redirect functions
  /\bredirect\s*\(/i,
  /\bnavigate\s*\(/i,
  // Next.js router
  /router\.(push|replace)\s*\(/i,
  /useRouter\(\)\.(push|replace)/i,
  // React Router
  /\buseNavigate\b/i,
  // Window location
  /window\.location\s*(=|\.href|\.assign|\.replace)/i,
  // Response redirect
  /Response\.redirect\s*\(/i,
  /NextResponse\.redirect\s*\(/i,
  // HTTP redirect
  /res\.(redirect|send|status\(\d{3}\))/i,
]

/**
 * Check if a line contains a React state setter (NOT a redirect)
 */
export function isReactStateSetter(line: string): boolean {
  return REACT_STATE_SETTER_PATTERNS.some(pattern => pattern.test(line))
}

/**
 * Check if a line contains an actual redirect/navigation
 */
export function isActualRedirect(line: string): boolean {
  return REDIRECT_PATTERNS.some(pattern => pattern.test(line))
}

/**
 * Determine if user input to this function is a security concern
 * State setters with user input are NOT redirects
 *
 * @param line - The line content
 * @returns 'state_setter' | 'redirect' | 'unknown'
 */
export function classifyNavigationIntent(
  line: string
): 'state_setter' | 'redirect' | 'unknown' {
  if (isReactStateSetter(line)) {
    return 'state_setter'
  }
  if (isActualRedirect(line)) {
    return 'redirect'
  }
  return 'unknown'
}

// ============================================================================
// Error Code vs Error Value Detection
// ============================================================================

/**
 * Check if a string in an error is a CODE (like 'SAME_PASSWORD')
 * vs an actual VALUE that might expose data
 */
export function isErrorCodeString(line: string): boolean {
  // Error codes are SCREAMING_CASE strings
  const errorCodePatterns = [
    // throw new Error('SAME_PASSWORD')
    /Error\s*\(\s*['"][A-Z][A-Z_0-9]*['"]\s*\)/,
    // throw new Error('USER_NOT_FOUND')
    /throw\s+.*['"][A-Z][A-Z_0-9]*['"]/,
    // ChatSDKError('unauthorized:INVALID_TOKEN')
    /Error\s*\(\s*['"][a-z]+:[A-Z_]+['"]\s*\)/,
  ]

  return errorCodePatterns.some(pattern => pattern.test(line))
}

/**
 * Check if an error message might contain actual password/secret value
 */
export function hasPasswordValueInError(line: string): boolean {
  // Only flag if actual password variable is concatenated into error
  const dangerousPatterns = [
    // Error('Password is: ' + password)
    /Error\s*\([^)]*\+\s*password[^)]*\)/i,
    // Error(`Password is: ${password}`)
    /Error\s*\([^)]*\$\{\s*password\s*\}[^)]*\)/i,
    // Error(JSON.stringify({...password}))
    /Error\s*\(\s*JSON\.stringify\s*\([^)]*password/i,
    // Error(secret)
    /Error\s*\(\s*(password|secret|token|apiKey)\s*\)/i,
  ]

  return dangerousPatterns.some(pattern => pattern.test(line))
}

/**
 * Check if "password" in error message is actually an error code/type
 */
export function isPasswordErrorCode(line: string): boolean {
  // These are error CODES about passwords, not password VALUES
  const passwordCodePatterns = [
    /['"]SAME_PASSWORD['"]/i,
    /['"]INVALID_PASSWORD['"]/i,
    /['"]WEAK_PASSWORD['"]/i,
    /['"]PASSWORD_REQUIRED['"]/i,
    /['"]PASSWORD_MISMATCH['"]/i,
    /['"]PASSWORD_TOO_SHORT['"]/i,
    /['"]PASSWORD_TOO_LONG['"]/i,
    /['"]PASSWORD_EXPIRED['"]/i,
    /['"]password:[\w_]+['"]/i,  // password:INVALID, password:MISMATCH
  ]

  return passwordCodePatterns.some(pattern => pattern.test(line))
}

// ============================================================================
// Signed URL Detection
// ============================================================================

/**
 * Check if a URL pattern is an intentional signed/presigned URL
 * These are FEATURES, not vulnerabilities
 */
export function isSignedUrlPattern(line: string): boolean {
  const signedUrlPatterns = [
    // AWS S3 presigned URLs
    /presign/i,
    /getSignedUrl/i,
    /presignedUrl/i,
    /presigned/i,
    // Azure SAS tokens
    /sasToken/i,
    /SharedAccessSignature/i,
    // GCP signed URLs
    /generateSignedUrl/i,
    /signedUrl/i,
    // Generic signed URL patterns
    /signature\s*[=:]/i,
    /signed\s*[=:]/i,
    /token\s*=.*&expires/i,
    /expires\s*=.*&signature/i,
  ]

  return signedUrlPatterns.some(pattern => pattern.test(line))
}

// ============================================================================
// Form Library Context Detection
// ============================================================================

/**
 * Check if shouldValidate: false is in a React Hook Form context
 * In RHF, this is a PERFORMANCE optimization, not a security bypass
 */
export function isReactHookFormContext(content: string, lineNumber: number): boolean {
  const lines = content.split('\n')
  const contextStart = Math.max(0, lineNumber - 20)
  const contextEnd = Math.min(lines.length, lineNumber + 5)
  const context = lines.slice(contextStart, contextEnd).join('\n')

  const rhfPatterns = [
    // useForm hook
    /useForm\s*[<(]/,
    /useForm\(\)/,
    // react-hook-form import
    /from\s+['"]react-hook-form['"]/,
    // Form methods
    /\bform\.(setValue|watch|reset|getValues|trigger|clearErrors)\b/,
    /\.(setValue|watch|reset|getValues|trigger|clearErrors)\s*\(/,
    // Register pattern
    /register\s*\(/,
    // FormProvider
    /FormProvider/,
    // Control pattern
    /control\s*=/,
  ]

  return rhfPatterns.some(pattern => pattern.test(context))
}

/**
 * Check if validation: false / validate: false is form library optimization
 */
export function isFormLibraryOptimization(line: string, content: string, lineNumber: number): boolean {
  // If in React Hook Form context, it's optimization
  if (isReactHookFormContext(content, lineNumber)) {
    return true
  }

  // Check for other form library contexts
  const formLibraryPatterns = [
    /formik/i,
    /react-final-form/i,
    /vee-validate/i,
    /vuelidate/i,
  ]

  const lines = content.split('\n')
  const contextStart = Math.max(0, lineNumber - 20)
  const context = lines.slice(contextStart, lineNumber + 5).join('\n')

  return formLibraryPatterns.some(pattern => pattern.test(context))
}

// ============================================================================
// Combined Intent Classification
// ============================================================================

export interface IntentAnalysis {
  /** The detected intent */
  intent: 'security_concern' | 'safe_pattern' | 'unknown'
  /** Reason for classification */
  reason: string
  /** Suggested action */
  action: 'flag' | 'skip' | 'downgrade'
}

/**
 * Analyze a line for security intent based on multiple heuristics
 */
export function analyzeSecurityIntent(
  line: string,
  content: string,
  lineNumber: number,
  patternType: 'redirect' | 'password_error' | 'token_url' | 'validation_bypass'
): IntentAnalysis {
  switch (patternType) {
    case 'redirect':
      if (isReactStateSetter(line)) {
        return {
          intent: 'safe_pattern',
          reason: 'React state setter, not a redirect',
          action: 'skip',
        }
      }
      if (isActualRedirect(line)) {
        return {
          intent: 'security_concern',
          reason: 'Actual redirect/navigation function',
          action: 'flag',
        }
      }
      break

    case 'password_error':
      if (isErrorCodeString(line) || isPasswordErrorCode(line)) {
        return {
          intent: 'safe_pattern',
          reason: 'Error code string, not actual password value',
          action: 'skip',
        }
      }
      if (hasPasswordValueInError(line)) {
        return {
          intent: 'security_concern',
          reason: 'Actual password value in error message',
          action: 'flag',
        }
      }
      break

    case 'token_url':
      if (isSignedUrlPattern(line)) {
        return {
          intent: 'safe_pattern',
          reason: 'Intentional signed/presigned URL pattern',
          action: 'skip',
        }
      }
      break

    case 'validation_bypass':
      if (isFormLibraryOptimization(line, content, lineNumber)) {
        return {
          intent: 'safe_pattern',
          reason: 'Form library performance optimization',
          action: 'skip',
        }
      }
      break
  }

  return {
    intent: 'unknown',
    reason: 'Could not determine intent',
    action: 'flag', // Conservative: flag if unknown
  }
}
