#!/bin/bash

# TimeSafari PlatformServiceMixin Migration Validation Script
# Author: Matthew Raymer
# 
# This script validates the migration status from legacy patterns to PlatformServiceMixin
# and provides detailed reporting on migration progress.

set -e

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

echo -e "${BLUE}🔍 TimeSafari PlatformServiceMixin Migration Validation${NC}"
echo "=================================================="

# Initialize counters
total_issues=0
legacy_db_imports=0
legacy_log_imports=0
direct_platform_usage=0
mixin_usage=0
mixed_pattern_count=0
technically_compliant_count=0
needs_human_testing_count=0
human_tested_count=0

# Function to log with timestamp
log_with_timestamp() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# Function to check for legacy patterns
check_legacy_patterns() {
    echo -e "\n${YELLOW}📋 Checking for legacy patterns...${NC}"
    
    # Check for legacy databaseUtil imports
    echo -n "  Checking databaseUtil imports... "
    legacy_db_files=$(find src -name "*.vue" -o -name "*.ts" | xargs grep -l "import.*databaseUtil" 2>/dev/null || true)
    if [ -n "$legacy_db_files" ]; then
        legacy_db_imports=$(echo "$legacy_db_files" | wc -l)
    else
        legacy_db_imports=0
    fi
    
    if [ "$legacy_db_imports" -gt 0 ]; then
        echo -e "${RED}Found $legacy_db_imports files${NC}"
        echo "    Files with legacy databaseUtil imports:"
        echo "$legacy_db_files" | sed 's/^/      /'
        total_issues=$((total_issues + legacy_db_imports))
    else
        echo -e "${GREEN}✓ None found${NC}"
    fi
    
    # Check for legacy logging imports
    echo -n "  Checking logConsoleAndDb imports... "
    legacy_log_files=$(find src -name "*.vue" -o -name "*.ts" | xargs grep -l "logConsoleAndDb" 2>/dev/null || true)
    if [ -n "$legacy_log_files" ]; then
        legacy_log_imports=$(echo "$legacy_log_files" | wc -l)
    else
        legacy_log_imports=0
    fi
    
    if [ "$legacy_log_imports" -gt 0 ]; then
        echo -e "${RED}Found $legacy_log_imports files${NC}"
        echo "    Files with legacy logging imports:"
        echo "$legacy_log_files" | sed 's/^/      /'
        total_issues=$((total_issues + legacy_log_imports))
    else
        echo -e "${GREEN}✓ None found${NC}"
    fi
    
    # Check for direct PlatformServiceFactory usage
    echo -n "  Checking direct PlatformServiceFactory usage... "
    direct_platform_files=$(find src -name "*.vue" -o -name "*.ts" | xargs grep -l "PlatformServiceFactory.getInstance" 2>/dev/null || true)
    if [ -n "$direct_platform_files" ]; then
        direct_platform_usage=$(echo "$direct_platform_files" | wc -l)
    else
        direct_platform_usage=0
    fi
    
    if [ "$direct_platform_usage" -gt 0 ]; then
        echo -e "${YELLOW}Found $direct_platform_usage files${NC}"
        echo "    Files with direct PlatformService usage:"
        echo "$direct_platform_files" | sed 's/^/      /'
    else
        echo -e "${GREEN}✓ None found${NC}"
    fi
}

# Function to check for positive patterns (mixin usage)
check_positive_patterns() {
    echo -e "\n${YELLOW}📈 Checking for modern patterns...${NC}"
    
    # Check for PlatformServiceMixin usage
    echo -n "  Checking PlatformServiceMixin usage... "
    mixin_files=$(find src -name "*.vue" | xargs grep -l "PlatformServiceMixin" 2>/dev/null || true)
    if [ -n "$mixin_files" ]; then
        mixin_usage=$(echo "$mixin_files" | wc -l)
    else
        mixin_usage=0
    fi
    
    if [ "$mixin_usage" -gt 0 ]; then
        echo -e "${GREEN}Found $mixin_usage files${NC}"
        echo "    Files using PlatformServiceMixin:"
        echo "$mixin_files" | sed 's/^/      /'
    else
        echo -e "${RED}No files found using mixin${NC}"
    fi
    
    # Check for mixin method usage
    echo -n "  Checking mixin method usage... "
    mixin_methods_count=$(find src -name "*.vue" | xargs grep -h '\$db\|this\.\$query\|this\.\$getAllContacts\|this\.\$settings\|this\.\$log' 2>/dev/null | wc -l || echo "0")
    
    if [ "$mixin_methods_count" -gt 0 ]; then
        echo -e "${GREEN}Found $mixin_methods_count usages${NC}"
    else
        echo -e "${YELLOW}No mixin method usages found${NC}"
    fi
}

# Function to analyze specific migration patterns
analyze_migration_patterns() {
    echo -e "\n${YELLOW}🔬 Analyzing migration patterns...${NC}"
    
    # Components that should use mixin but don't
    echo -n "  Components with database operations but no mixin... "
    db_components_no_mixin=$(find src -name "*.vue" -exec bash -c '
        if grep -q "dbQuery\|dbExec\|dbGetOneRow" "$1" && ! grep -q "PlatformServiceMixin" "$1"; then
            echo "$1"
        fi
    ' _ {} \;)
    
    if [ -n "$db_components_no_mixin" ]; then
        db_components_no_mixin_count=$(echo "$db_components_no_mixin" | wc -l)
    else
        db_components_no_mixin_count=0
    fi
    
    if [ "$db_components_no_mixin_count" -gt 0 ]; then
        echo -e "${RED}Found $db_components_no_mixin_count components${NC}"
        echo "    Components needing mixin:"
        echo "$db_components_no_mixin" | sed 's/^/      /'
        total_issues=$((total_issues + db_components_no_mixin_count))
    else
        echo -e "${GREEN}✓ All components with DB operations use mixin${NC}"
    fi
    
    # Check for mixed patterns in same file (excluding comments)
    echo -n "  Files with mixed patterns... "
    mixed_pattern_files=$(find src -name "*.vue" -exec bash -c '
        if grep -q "PlatformServiceMixin" "$1"; then
            # Check for legacy patterns in actual code (not comments)
            if grep -v "^[[:space:]]*//\|^[[:space:]]*\*\|^[[:space:]]*#" "$1" | grep -q "databaseUtil\|logConsoleAndDb"; then
                echo "$1"
            fi
        fi
    ' _ {} \;)
    
    if [ -n "$mixed_pattern_files" ]; then
        mixed_pattern_count=$(echo "$mixed_pattern_files" | wc -l)
    else
        mixed_pattern_count=0
    fi
    
    if [ "$mixed_pattern_count" -gt 0 ]; then
        echo -e "${YELLOW}Found $mixed_pattern_count files${NC}"
        echo "    Files with mixed patterns (partially migrated):"
        echo "$mixed_pattern_files" | sed 's/^/      /'
    else
        echo -e "${GREEN}✓ No mixed patterns found${NC}"
    fi
    
    # Check for technically compliant files (mixin + no legacy code)
    echo -n "  Technically compliant files... "
    technically_compliant_files=$(find src -name "*.vue" -exec bash -c '
        if grep -q "PlatformServiceMixin" "$1" && ! grep -v "^[[:space:]]*//\|^[[:space:]]*\*\|^[[:space:]]*#" "$1" | grep -q "databaseUtil\|logConsoleAndDb"; then
            echo "$1"
        fi
    ' _ {} \;)
    
    if [ -n "$technically_compliant_files" ]; then
        technically_compliant_count=$(echo "$technically_compliant_files" | wc -l)
    else
        technically_compliant_count=0
    fi
    
    if [ "$technically_compliant_count" -gt 0 ]; then
        echo -e "${GREEN}Found $technically_compliant_count files${NC}"
        echo "    Technically compliant files (use mixin, no legacy code):"
        echo "$technically_compliant_files" | sed 's/^/      /'
    else
        echo -e "${YELLOW}No technically compliant files found${NC}"
    fi
}

# Function to check human testing status
check_human_testing_status() {
    echo -e "\n${YELLOW}🧪 Human Testing Status${NC}"
    echo "====================="
    
    # Known human tested files (confirmed by user)
    human_tested_files="
    src/views/ClaimAddRawView.vue
    src/views/LogView.vue
    "
    
    # Files requiring human testing (technically compliant but not tested)
    echo -n "  Files requiring human testing... "
    needs_human_testing=$(echo "$technically_compliant_files" | grep -v -F "$human_tested_files" | grep -v "^[[:space:]]*$" || true)
    if [ -n "$needs_human_testing" ]; then
        needs_human_testing_count=$(echo "$needs_human_testing" | grep -v "^[[:space:]]*$" | wc -l)
    else
        needs_human_testing_count=0
    fi
    
    if [ "$needs_human_testing_count" -gt 0 ]; then
        echo -e "${YELLOW}Found $needs_human_testing_count files${NC}"
        echo "    Files needing human testing validation:"
        echo "$needs_human_testing" | sed 's/^/      /'
    else
        echo -e "${GREEN}✓ All compliant files have been human tested${NC}"
    fi
    
    # Files with confirmed human testing
    echo -n "  Human tested files... "
    if [ -n "$human_tested_files" ]; then
        human_tested_count=$(echo "$human_tested_files" | grep -v "^[[:space:]]*$" | wc -l)
    else
        human_tested_count=0
    fi
    
    if [ "$human_tested_count" -gt 0 ]; then
        echo -e "${GREEN}Found $human_tested_count files${NC}"
        echo "    Files with confirmed human testing:"
        echo "$human_tested_files" | sed 's/^/      /'
    else
        echo -e "${YELLOW}No confirmed human testing yet${NC}"
    fi
}

# Function to generate migration report
generate_report() {
    echo -e "\n${BLUE}📊 Migration Status Report${NC}"
    echo "=============================="
    
    total_vue_files=$(find src -name "*.vue" | wc -l)
    # Handle division by zero
    if [ "$total_vue_files" -gt 0 ]; then
        migration_percentage=$((mixin_usage * 100 / total_vue_files))
    else
        migration_percentage=0
    fi
    
    echo "Total Vue components: $total_vue_files"
    echo "Components using PlatformServiceMixin: $mixin_usage"
    echo "Migration percentage: ${migration_percentage}%"
    echo ""
    echo "Technical Migration Status:"
    echo "  - Technically compliant files: $technically_compliant_count"
    echo "  - Mixed pattern files: $mixed_pattern_count"
    # Ensure variables are numeric for arithmetic
    total_vue_files_num=${total_vue_files:-0}
    technically_compliant_num=${technically_compliant_count:-0}
    mixed_pattern_num=${mixed_pattern_count:-0}
    files_needing_migration=$((total_vue_files_num - technically_compliant_num - mixed_pattern_num))
    echo "  - Files needing migration: $files_needing_migration"
    echo ""
    echo "Legacy patterns found:"
    echo "  - databaseUtil imports: $legacy_db_imports"
    echo "  - logConsoleAndDb imports: $legacy_log_imports"
    echo "  - Direct PlatformService usage: $direct_platform_usage"
    echo ""
    echo "Human Testing Status:"
    echo "  - Human tested files: $human_tested_count"
    echo "  - Awaiting human testing: $needs_human_testing_count"
    echo ""
    echo "Total issues requiring attention: $total_issues"
    
    # Generate priority list
    if [ "$total_issues" -gt 0 ]; then
        echo -e "\n${YELLOW}🎯 Priority Migration List${NC}"
        echo "========================="
        
        if [ "$legacy_db_imports" -gt 0 ]; then
            echo "1. HIGH PRIORITY: Migrate databaseUtil imports ($legacy_db_imports files)"
        fi
        
        if [ "$legacy_log_imports" -gt 0 ]; then
            echo "2. HIGH PRIORITY: Migrate logging patterns ($legacy_log_imports files)"
        fi
        
        if [ "$mixed_pattern_count" -gt 0 ]; then
            echo "3. HIGH PRIORITY: Complete mixed pattern migrations ($mixed_pattern_count files)"
        fi
        
        if [ "$needs_human_testing_count" -gt 0 ]; then
            echo "4. MEDIUM PRIORITY: Human testing validation ($needs_human_testing_count files)"
        fi
        
        if [ "$direct_platform_usage" -gt 0 ]; then
            echo "5. LOW PRIORITY: Consider migrating direct PlatformService usage ($direct_platform_usage files)"
        fi
    fi
}

# Function to suggest next steps
suggest_next_steps() {
    echo -e "\n${BLUE}🚀 Suggested Next Steps${NC}"
    echo "======================"
    
    if [ "$total_issues" -eq 0 ]; then
        echo -e "${GREEN}✅ Migration appears complete!${NC}"
        echo "1. Run comprehensive tests to verify functionality"
        echo "2. Set up ESLint rules to prevent regression"
        echo "3. Update documentation to reflect new patterns"
    else
        echo "1. Start with high-priority files (databaseUtil and logging)"
        echo "2. Use the migration template: docs/migration-templates/component-migration.md"
        echo "3. Test each component after migration"
        echo "4. Set up ESLint rules to prevent new legacy usage"
        echo "5. Re-run this script to track progress"
    fi
}

# Function to validate TypeScript compilation
validate_typescript() {
    echo -e "\n${YELLOW}🔧 Validating TypeScript compilation...${NC}"
    
    if command -v npx >/dev/null 2>&1; then
        echo -n "  Running TypeScript check... "
        if npx tsc --noEmit --skipLibCheck >/dev/null 2>&1; then
            echo -e "${GREEN}✓ TypeScript compilation successful${NC}"
        else
            echo -e "${RED}✗ TypeScript compilation failed${NC}"
            echo "    Run 'npx tsc --noEmit' for details"
            total_issues=$((total_issues + 1))
        fi
    else
        echo -e "${YELLOW}  TypeScript not available, skipping compilation check${NC}"
    fi
}

# Main execution
main() {
    log_with_timestamp "Starting migration validation..."
    
    check_legacy_patterns
    check_positive_patterns
    analyze_migration_patterns
    check_human_testing_status
    validate_typescript
    generate_report
    suggest_next_steps
    
    echo -e "\n${BLUE}===========================================${NC}"
    
    if [ "$total_issues" -eq 0 ]; then
        echo -e "${GREEN}✅ Migration validation passed!${NC}"
        log_with_timestamp "Migration validation completed successfully"
        exit 0
    else
        echo -e "${YELLOW}⚠️  Migration validation found $total_issues issues${NC}"
        log_with_timestamp "Migration validation completed with issues"
        exit 1
    fi
}

# Run main function
main "$@" 