#!/bin/bash
# ============================================
# Enhanced File Watcher Hook with Hard Reset for Claude Code
# Automatically triggers Docker hard resets and syncs all files
# ============================================

# Configuration
LOG_FILE="/tmp/file-watcher-hook.log"
DOCKER_UPDATE_TRIGGER="/tmp/docker-update-needed"
PROJECT_ROOT="/Users/Asim/Desktop/mawidi_codex"
MAWIDI_SITE_DIR="$PROJECT_ROOT/mawidi-site"

# Function to log messages with timestamp
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"  # Also echo to stdout
}

# Function to perform hard reset and sync all files to Docker
hard_reset_docker() {
    log_message "🔄 STARTING HARD RESET AND DOCKER SYNC"

    # Check if Docker is running
    if ! docker info &>/dev/null; then
        log_message "⚠️ Docker is not running. Starting Docker..."
        open -a Docker
        sleep 10
    fi

    # Stop all containers for clean state
    log_message "🛑 Stopping all Docker containers..."
    cd "$PROJECT_ROOT"
    docker-compose down --remove-orphans 2>/dev/null || true

    # Clear Docker build cache for fresh rebuild
    log_message "🧹 Clearing Docker build cache..."
    docker builder prune -f 2>/dev/null || true

    # Remove old containers and volumes
    log_message "🗑️ Removing old containers and volumes..."
    docker container prune -f 2>/dev/null || true
    docker volume prune -f 2>/dev/null || true

    # Sync all project files (force copy)
    log_message "📁 Syncing all project files to Docker context..."

    # Rebuild images with no cache for complete refresh
    log_message "🔨 Rebuilding Docker images (no cache)..."
    cd "$PROJECT_ROOT"
    docker-compose build --no-cache

    # Start containers with fresh build
    log_message "🚀 Starting fresh Docker containers..."
    docker-compose up -d

    # Wait for services to be ready
    log_message "⏳ Waiting for services to be ready..."
    sleep 5

    # Verify containers are running
    if docker-compose ps | grep -q "Up"; then
        log_message "✅ Docker hard reset completed successfully!"

        # Send success notification
        if command -v osascript &> /dev/null; then
            osascript -e 'display notification "All files synced and containers rebuilt" with title "Docker Hard Reset Complete" sound name "Glass"'
        fi
    else
        log_message "❌ Docker containers failed to start properly"

        # Send error notification
        if command -v osascript &> /dev/null; then
            osascript -e 'display notification "Please check Docker logs" with title "Docker Reset Failed" sound name "Basso"'
        fi
    fi

    # Show container status
    docker-compose ps

    log_message "📊 Current Docker status:"
    docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
}

# Function to sync specific files to Docker volumes
sync_files_to_docker() {
    local file_path="$1"

    log_message "📤 Syncing file to Docker: $file_path"

    # Get container name
    local container_name="mawidi-site"

    # Check if container is running
    if docker ps --format '{{.Names}}' | grep -q "$container_name"; then
        # Copy file to container
        if [[ -f "$file_path" ]]; then
            # Calculate relative path from project root
            local relative_path="${file_path#$PROJECT_ROOT/}"

            # Copy to container
            docker cp "$file_path" "$container_name:/app/$relative_path" 2>/dev/null || {
                log_message "⚠️ Failed to sync $file_path to container"
            }

            log_message "✓ Synced: $relative_path"
        fi
    else
        log_message "⚠️ Container $container_name not running, triggering hard reset"
        hard_reset_docker
    fi
}

# Function to detect task completion
detect_task_completion() {
    local event_type="$1"
    local file_path="$2"

    # Trigger hard reset on specific events
    if [[ "$event_type" == "task_complete" ]] || \
       [[ "$event_type" == "prompt_complete" ]] || \
       [[ "$file_path" == *"TASK_COMPLETE"* ]]; then
        log_message "🎯 Task completion detected - triggering hard reset"
        return 0
    fi

    # Also trigger on significant file changes
    local filename=$(basename "$file_path")
    if [[ "$filename" == "package.json" ]] || \
       [[ "$filename" == "package-lock.json" ]] || \
       [[ "$filename" == "Dockerfile"* ]] || \
       [[ "$filename" == "docker-compose"*.yml ]] || \
       [[ "$filename" == ".env"* ]]; then
        log_message "🔧 Critical file changed - triggering hard reset"
        return 0
    fi

    return 1
}

# Main hook logic
main() {
    local event_type="${1:-file_changed}"
    local file_path="${2:-}"

    # Always log the event
    log_message "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_message "📍 Event: $event_type"
    log_message "📄 File: $file_path"

    # Check if this is a task completion or significant change
    if detect_task_completion "$event_type" "$file_path"; then
        # Perform hard reset immediately
        hard_reset_docker

        # Mark update as complete
        echo "hard_reset_complete" > "$DOCKER_UPDATE_TRIGGER"

        log_message "🎉 AUTO-SYNC COMPLETE: All files updated in Docker"
        echo "🎉 AUTO-SYNC COMPLETE: All files updated in Docker"

    elif [[ -n "$file_path" ]] && [[ -f "$file_path" ]]; then
        # For individual file changes, sync immediately
        sync_files_to_docker "$file_path"

        # Check if we need to restart services
        local filename=$(basename "$file_path")
        if [[ "$filename" == *.tsx ]] || \
           [[ "$filename" == *.ts ]] || \
           [[ "$filename" == *.jsx ]] || \
           [[ "$filename" == *.js ]]; then
            log_message "⚡ Hot reload will handle: $filename"
        fi
    else
        # Default action: trigger hard reset for safety
        log_message "🔄 Default action: Triggering hard reset for consistency"
        hard_reset_docker
    fi

    log_message "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}

# Trap to ensure cleanup on exit
trap 'log_message "Hook terminated"' EXIT

# Run the hook
main "$@"

# Always return success to not block Claude Code
exit 0