#!/bin/bash

# Migration Coordinator Script
# Orchestrates the complete migration process
# Usage: ./migration_coordinator.sh [phase]

set -e  # Exit on any error

PHASE=${1:-"all"}

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

log() {
    echo -e "${BLUE}[$(date +'%H:%M:%S')]${NC} $1"
}

success() {
    echo -e "${GREEN}✅${NC} $1"
}

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

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

# Ensure we're on config-driven branch
if [ "$(git branch --show-current)" != "config-driven" ]; then
    error "Not on config-driven branch. Run: git checkout config-driven"
    exit 1
fi

# Create state directory if it doesn't exist
mkdir -p .migration/state

# Function to commit progress
commit_progress() {
    local message="$1"
    git add -A
    git commit --no-gpg-sign -m "$message" || true
    log "Committed: $message"
}

# Phase 1: Analysis
phase_analysis() {
    log "🔍 Phase 1: Analysis"

    log "Running syntax analysis..."
    chmod +x .migration/agents/01_analyze_syntax.sh
    ./.migration/agents/01_analyze_syntax.sh

    log "Running ENV reference analysis..."
    chmod +x .migration/agents/03_analyze_env.sh
    ./.migration/agents/03_analyze_env.sh

    commit_progress "chore: complete analysis phase - syntax and env references"
    success "Analysis phase complete"
}

# Phase 2: Fix Syntax Errors
phase_syntax_fixes() {
    log "🔧 Phase 2: Syntax Fixes"

    if [ ! -f ".migration/state/syntax_analysis.json" ]; then
        warning "No syntax analysis found. Running analysis first..."
        phase_analysis
    fi

    # Get files with syntax errors (simplified - in practice would parse JSON)
    log "Applying syntax fixes to critical files..."
    chmod +x .migration/agents/02_fix_syntax.sh

    # Fix high-priority files first
    FILES_TO_FIX=(
        "core/nulib/servers/ssh.nu"
        "core/nulib/servers/status.nu"
        "core/nulib/servers/state.nu"
        "core/nulib/main_provisioning/create.nu"
        "core/nulib/main_provisioning/delete.nu"
        "core/nulib/main_provisioning/update.nu"
    )

    for file in "${FILES_TO_FIX[@]}"; do
        if [ -f "$file" ]; then
            log "Fixing syntax in $file..."
            ./.migration/agents/02_fix_syntax.sh "$file" || warning "Failed to fix $file"
        fi
    done

    commit_progress "fix: apply syntax corrections to core files"
    success "Syntax fixes phase complete"
}

# Phase 3: Migrate ENV References
phase_env_migration() {
    log "🔄 Phase 3: ENV Migration"

    chmod +x .migration/agents/04_migrate_env.sh

    # Migrate modules in order of dependency
    MODULES=(
        "core/nulib/lib_provisioning/utils"
        "core/nulib/servers"
        "core/nulib/taskservs"
        "core/nulib/main_provisioning"
    )

    for module_dir in "${MODULES[@]}"; do
        if [ -d "$module_dir" ]; then
            log "Migrating ENV references in $module_dir..."
            for file in "$module_dir"/*.nu; do
                if [ -f "$file" ]; then
                    log "  Processing $file..."
                    ./.migration/agents/04_migrate_env.sh "$file" || warning "Failed to migrate $file"
                fi
            done
        fi
    done

    commit_progress "refactor: migrate ENV references to config accessors"
    success "ENV migration phase complete"
}

# Phase 4: Testing
phase_testing() {
    log "🧪 Phase 4: Testing"

    chmod +x .migration/agents/05_test_module.sh

    MODULES=("utils" "servers" "taskservs" "main")

    for module in "${MODULES[@]}"; do
        log "Testing $module module..."
        ./.migration/agents/05_test_module.sh "$module" || warning "Testing failed for $module"
    done

    commit_progress "test: validate migrated modules"
    success "Testing phase complete"
}

# Phase 5: Final Validation
phase_validation() {
    log "✅ Phase 5: Final Validation"

    log "Running comprehensive validation..."

    # Test main commands
    if ./core/nulib/provisioning help >/dev/null 2>&1; then
        success "Main provisioning command works"
    else
        error "Main provisioning command failed"
    fi

    if ./core/nulib/provisioning server help >/dev/null 2>&1; then
        success "Server module works"
    else
        warning "Server module has issues"
    fi

    commit_progress "chore: final validation complete"
    success "Migration validation complete"
}

# Main execution
main() {
    log "🚀 Starting Config-Driven Migration"
    log "Phase: $PHASE"

    case $PHASE in
        "analysis"|"1")
            phase_analysis
            ;;
        "syntax"|"2")
            phase_syntax_fixes
            ;;
        "env"|"3")
            phase_env_migration
            ;;
        "test"|"4")
            phase_testing
            ;;
        "validate"|"5")
            phase_validation
            ;;
        "all")
            phase_analysis
            phase_syntax_fixes
            phase_env_migration
            phase_testing
            phase_validation
            success "🎉 Complete migration finished!"
            ;;
        *)
            echo "Usage: $0 [analysis|syntax|env|test|validate|all]"
            exit 1
            ;;
    esac
}

# Run main function
main "$@"