#!/bin/bash

# ================================================================================
# TypeScript TS4111 Fix - Process.env Bracket Notation Converter
# ================================================================================
# Converts: process.env.NODE_ENV → process.env['NODE_ENV']
# Fixes: 840 TS4111 errors caused by noPropertyAccessFromIndexSignature
# ================================================================================

set -e

echo "🔧 TypeScript TS4111 Fixer"
echo "=========================="
echo ""

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Counter
TOTAL_FILES=0
MODIFIED_FILES=0

# Backup directory
BACKUP_DIR=".ts-backup-$(date +%Y%m%d-%H%M%S)"

echo "📁 Creating backup: $BACKUP_DIR"
mkdir -p "$BACKUP_DIR"

# Find all TypeScript files
echo ""
echo "🔍 Scanning TypeScript files..."
FILES=$(find apps packages -name "*.ts" -not -path "*/node_modules/*" -not -path "*/dist/*" -not -path "*/.turbo/*" -type f)

for file in $FILES; do
  TOTAL_FILES=$((TOTAL_FILES + 1))
  
  # Check if file contains process.env.VARIABLE pattern
  if grep -q "process\.env\.[A-Z_][A-Z0-9_]*" "$file"; then
    echo "  ✏️  Processing: $file"
    
    # Create backup
    backup_path="$BACKUP_DIR/$file"
    mkdir -p "$(dirname "$backup_path")"
    cp "$file" "$backup_path"
    
    # Fix the file (macOS compatible sed)
    sed -i '' -E 's/process\.env\.([A-Z_][A-Z0-9_]*)/process.env["\1"]/g' "$file"
    
    MODIFIED_FILES=$((MODIFIED_FILES + 1))
  fi
done

echo ""
echo "📊 Results:"
echo "  Total files scanned: $TOTAL_FILES"
echo "  Files modified: $MODIFIED_FILES"
echo ""

if [ $MODIFIED_FILES -gt 0 ]; then
  echo -e "${GREEN}✅ Success!${NC}"
  echo ""
  echo "🔍 Verifying changes..."
  echo ""
  
  # Show sample of changes
  echo "Sample changes (first 5 files):"
  find apps packages -name "*.ts" -not -path "*/node_modules/*" -type f | head -5 | while read file; do
    if grep -q "process\.env\[" "$file"; then
      echo ""
      echo "  📄 $file"
      grep -n "process\.env\[" "$file" | head -3 | sed 's/^/    /'
    fi
  done
  
  echo ""
  echo "💾 Backup location: $BACKUP_DIR"
  echo ""
  echo "🧪 Next steps:"
  echo "  1. Review changes: git diff"
  echo "  2. Run type-check: pnpm type-check"
  echo "  3. Test application: pnpm dev"
  echo ""
  echo "⚠️  To revert: cp -r $BACKUP_DIR/* ."
else
  echo -e "${YELLOW}⚠️  No files needed modification${NC}"
  rm -rf "$BACKUP_DIR"
fi

echo ""
echo "Done! 🎉"
