#!/bin/bash
# ============================================
# Post-Prompt Hook for Claude Code
# Automatically syncs all files to Docker after each prompt
# ============================================

PROJECT_ROOT="/Users/Asim/Desktop/mawidi_codex"
LOG_FILE="/tmp/post-prompt-hook.log"
WATCHER_HOOK="$PROJECT_ROOT/.claude/hooks/file-watcher-hook.sh"

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

# Main function
main() {
    log_message "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_message "🔄 POST-PROMPT SYNC INITIATED"

    # Check if any files were modified in the last prompt
    local recent_changes=$(find "$PROJECT_ROOT/mawidi-site" -type f \
        \( -name "*.tsx" -o -name "*.ts" -o -name "*.jsx" -o -name "*.js" \
           -o -name "*.css" -o -name "*.scss" -o -name "package.json" \
           -o -name "Dockerfile*" -o -name "docker-compose*.yml" \) \
        -mmin -1 2>/dev/null | wc -l)

    if [[ $recent_changes -gt 0 ]]; then
        log_message "📝 Detected $recent_changes file(s) changed in the last minute"
        log_message "🚀 Triggering automatic Docker hard reset..."

        # Call the file watcher hook with prompt_complete event
        if [[ -x "$WATCHER_HOOK" ]]; then
            "$WATCHER_HOOK" "prompt_complete" "AUTO_SYNC_ALL_FILES"
        else
            log_message "⚠️ Warning: File watcher hook not executable"
        fi
    else
        log_message "✅ No recent file changes detected"

        # Still sync Docker state to ensure consistency
        log_message "🔍 Verifying Docker state..."

        # Check if containers are running
        if ! docker ps --format '{{.Names}}' | grep -q "mawidi-site"; then
            log_message "⚠️ Containers not running - triggering reset"
            if [[ -x "$WATCHER_HOOK" ]]; then
                "$WATCHER_HOOK" "prompt_complete" "CONTAINER_CHECK_FAILED"
            fi
        else
            log_message "✅ Docker containers are running"
        fi
    fi

    log_message "🎯 POST-PROMPT SYNC COMPLETE"
    log_message "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}

# Run main function
main "$@"

# Always return success
exit 0