version: 1
kind: action
name: Refactor
description: Basic code refactoring and improvement
prompt: |
  Perform systematic code refactoring to improve code quality and maintainability.
  Identify common refactoring opportunities and apply best practices.
  Focus on reducing complexity while maintaining functionality.
  Use this for improving code structure and readability through targeted refactoring.
enhanced-prompt: |-
  # 🔧 Code Refactoring

  ## Code Analysis
  ```bash
  PROJECT_NAME=$(basename $(pwd))
  echo "🔧 Project: $PROJECT_NAME"

  # Create backup
  echo "💾 Creating backup..."
  if git status >/dev/null 2>&1; then
    git stash push -m "Pre-refactoring backup $(date)" 2>/dev/null || echo "No changes to backup"
    echo "✅ Backup completed with git stash"
  else
    echo "ℹ️ Not a git repository - manual backup recommended"
  fi
  ```

  ## Issue Identification
  ```bash
  echo "🔍 Analyzing code issues..."

  # Find large files
  echo "📄 Large files (500+ lines):"
  find src/ -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" 2>/dev/null | \
    xargs wc -l 2>/dev/null | awk '$1 > 500 {print "  - " $2 ": " $1 " lines"}' | head -5

  # Detect complex patterns
  echo "🧮 Complex code patterns:"
  NESTED_LOOPS=$(grep -r "for.*for\|while.*while" --include="*.js" --include="*.ts" src/ 2>/dev/null | wc -l)
  DEEP_NESTING=$(grep -r "if.*if.*if" --include="*.js" --include="*.ts" src/ 2>/dev/null | wc -l)
  echo "  - Nested loops: $NESTED_LOOPS"
  echo "  - Deep nesting: $DEEP_NESTING"

  # Check for outdated patterns
  echo "📊 Improvement opportunities:"
  VAR_COUNT=$(grep -r "var " --include="*.js" src/ 2>/dev/null | wc -l)
  CONSOLE_COUNT=$(grep -r "console.log" --include="*.js" --include="*.ts" src/ 2>/dev/null | wc -l)
  echo "  - var usage: $VAR_COUNT (recommend let/const)"
  echo "  - console.log: $CONSOLE_COUNT (recommend proper logging)"
  ```

  ## Validation & Testing
  ```bash
  echo "🧪 Refactoring validation:"

  # Run tests
  if [ -f "package.json" ]; then
    echo "🧪 Running tests..."
    if npm test >/dev/null 2>&1; then
      echo "✅ All tests passed"
    else
      echo "❌ Tests failed - requires fixes"
    fi
    
    # Run linting
    if npm run lint >/dev/null 2>&1; then
      echo "✅ Linting passed"
    else
      echo "⚠️ Linting errors found"
    fi
  fi
  ```

  **🎯 Result:** Systematic code improvement with quality validation
