#!/bin/bash

# Migration Helper Script for TimeSafari PlatformServiceMixin Migration
# This script helps track and automate the migration from databaseUtil to PlatformServiceMixin

set -e

echo "🔄 TimeSafari Migration Helper"
echo "================================"

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    print_error "Please run this script from the project root directory"
    exit 1
fi

# Function to count remaining databaseUtil imports
count_remaining_imports() {
    local count=$(find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" | wc -l)
    echo $count
}

# Function to show files with databaseUtil imports
show_remaining_files() {
    echo "📋 Files still importing databaseUtil:"
    echo "----------------------------------------"
    find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" | sort
    echo ""
}

# Function to show migration progress
show_progress() {
    local total_files=52  # Total files that need migration
    local remaining=$(count_remaining_imports)
    local migrated=$((total_files - remaining))
    local percentage=$((migrated * 100 / total_files))
    
    echo "📊 Migration Progress"
    echo "===================="
    echo "Total files to migrate: $total_files"
    echo "Files migrated: $migrated"
    echo "Files remaining: $remaining"
    echo "Progress: $percentage%"
    echo ""
    
    # Progress bar
    local filled=$((percentage / 2))
    local empty=$((50 - filled))
    printf "["
    for ((i=0; i<filled; i++)); do printf "█"; done
    for ((i=0; i<empty; i++)); do printf "░"; done
    printf "] $percentage%%\n\n"
}

# Function to show common replacement patterns
show_replacement_patterns() {
    echo "🔄 Common Replacement Patterns"
    echo "=============================="
    echo "generateInsertStatement → this.\$generateInsertStatement"
    echo "generateUpdateStatement → this.\$generateUpdateStatement"
    echo "parseJsonField → this._parseJsonField"
    echo "mapColumnsToValues → this._mapColumnsToValues"
    echo "logToDb → this.\$log"
    echo "logConsoleAndDb → this.\$logAndConsole"
    echo "memoryLogs → this.\$memoryLogs"
    echo ""
}

# Function to show migration template
show_migration_template() {
    echo "📝 Migration Template for Vue Components"
    echo "========================================"
    echo ""
    echo "1. Add PlatformServiceMixin import:"
    echo "   import { PlatformServiceMixin } from '@/utils/PlatformServiceMixin';"
    echo ""
    echo "2. Add mixin to component:"
    echo "   export default class ComponentName extends Vue {"
    echo "     mixins = [PlatformServiceMixin];"
    echo "     // ... rest of component"
    echo "   }"
    echo ""
    echo "3. Replace databaseUtil imports:"
    echo "   // Remove: import { ... } from '@/db/databaseUtil';"
    echo "   // Use mixin methods instead"
    echo ""
    echo "4. Update method calls:"
    echo "   // Before: generateInsertStatement(contact, 'contacts')"
    echo "   // After:  this.\$generateInsertStatement(contact, 'contacts')"
    echo ""
}

# Function to validate migration
validate_migration() {
    echo "🔍 Validating Migration"
    echo "======================"
    
    # Check for remaining databaseUtil imports
    local remaining=$(count_remaining_imports)
    if [ $remaining -eq 0 ]; then
        print_status "No databaseUtil imports found!"
    else
        print_warning "Found $remaining files still importing databaseUtil"
        show_remaining_files
    fi
    
    # Run linting
    echo "Running linting..."
    if npm run lint > /dev/null 2>&1; then
        print_status "Linting passed"
    else
        print_error "Linting failed - check output above"
    fi
    
    # Run type checking
    echo "Running type checking..."
    if npx tsc --noEmit > /dev/null 2>&1; then
        print_status "TypeScript compilation passed"
    else
        print_error "TypeScript compilation failed - check output above"
    fi
    
    echo ""
}

# Function to show next steps
show_next_steps() {
    echo "🎯 Next Steps"
    echo "============="
    echo ""
    
    local remaining=$(count_remaining_imports)
    
    if [ $remaining -eq 0 ]; then
        print_status "Migration complete! All files have been migrated."
        echo ""
        echo "Next actions:"
        echo "1. Run full test suite"
        echo "2. Test on all platforms (Web, Mobile, Desktop)"
        echo "3. Update documentation"
        echo "4. Remove databaseUtil file (if no longer needed)"
    else
        echo "Priority order for remaining $remaining files:"
        echo "1. Views (user-facing components)"
        echo "2. Components (reusable UI components)"
        echo "3. Services (business logic)"
        echo "4. Utils (utility functions)"
        echo ""
        echo "Use the migration template above for each file."
    fi
    
    echo ""
}

# Main menu
show_menu() {
    echo "Choose an option:"
    echo "1. Show migration progress"
    echo "2. Show remaining files"
    echo "3. Show replacement patterns"
    echo "4. Show migration template"
    echo "5. Validate migration"
    echo "6. Show next steps"
    echo "7. Run all checks"
    echo "8. Exit"
    echo ""
    read -p "Enter your choice (1-8): " choice
    
    case $choice in
        1)
            show_progress
            ;;
        2)
            show_remaining_files
            ;;
        3)
            show_replacement_patterns
            ;;
        4)
            show_migration_template
            ;;
        5)
            validate_migration
            ;;
        6)
            show_next_steps
            ;;
        7)
            show_progress
            show_remaining_files
            show_replacement_patterns
            validate_migration
            show_next_steps
            ;;
        8)
            print_info "Goodbye!"
            exit 0
            ;;
        *)
            print_error "Invalid choice. Please try again."
            ;;
    esac
}

# Check if arguments were provided
if [ $# -eq 0 ]; then
    # No arguments, show menu
    show_menu
else
    # Arguments provided, run specific function
    case $1 in
        "progress")
            show_progress
            ;;
        "files")
            show_remaining_files
            ;;
        "patterns")
            show_replacement_patterns
            ;;
        "template")
            show_migration_template
            ;;
        "validate")
            validate_migration
            ;;
        "next")
            show_next_steps
            ;;
        "all")
            show_progress
            show_remaining_files
            show_replacement_patterns
            validate_migration
            show_next_steps
            ;;
        *)
            print_error "Unknown argument: $1"
            echo "Usage: $0 [progress|files|patterns|template|validate|next|all]"
            exit 1
            ;;
    esac
fi 