#!/bin/bash
# ============================================
# Docker Auto-Update Daemon
# Runs in background and monitors file changes
# ============================================

DAEMON_PID_FILE="/tmp/docker-auto-daemon.pid"
DAEMON_LOG_FILE="/tmp/docker-auto-daemon.log"
WATCH_DIR="${1:-./mawidi-site}"
UPDATE_TRIGGER_FILE="/tmp/docker-update-needed"
STATE_FILE="/tmp/docker-auto-state.json"

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

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

# Function to save state
save_state() {
    cat > "$STATE_FILE" << EOF
{
    "enabled": true,
    "pid": $$,
    "started": "$(date -Iseconds)",
    "watch_dir": "$WATCH_DIR",
    "method": "$1"
}
EOF
    log "State saved: $1"
}

# Function to start daemon
start_daemon() {
    # Check if already running
    if [ -f "$DAEMON_PID_FILE" ]; then
        PID=$(cat "$DAEMON_PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo -e "${YELLOW}Docker auto-update daemon is already running (PID: $PID)${NC}"
            return 1
        fi
    fi

    echo -e "${BLUE}Starting Docker auto-update daemon...${NC}"

    # Start the daemon in background
    {
        echo $$ > "$DAEMON_PID_FILE"
        save_state "hot-reload"
        log "Daemon started with PID $$"

        # Start Docker development environment
        cd "$(dirname "$WATCH_DIR")" || exit 1
        make dev > /dev/null 2>&1 &
        DOCKER_PID=$!
        log "Docker dev started with PID $DOCKER_PID"

        # Monitor for update triggers
        while true; do
            if [ -f "$UPDATE_TRIGGER_FILE" ]; then
                UPDATE_TYPE=$(cat "$UPDATE_TRIGGER_FILE")
                rm "$UPDATE_TRIGGER_FILE"

                case "$UPDATE_TYPE" in
                    "rebuild")
                        log "Rebuilding Docker containers..."
                        docker-compose --profile dev build
                        docker-compose --profile dev up -d
                        ;;
                    "restart")
                        log "Restarting Docker containers..."
                        docker-compose --profile dev restart
                        ;;
                    *)
                        log "Unknown update type: $UPDATE_TYPE"
                        ;;
                esac
            fi
            sleep 2
        done
    } &

    DAEMON_PID=$!
    echo "$DAEMON_PID" > "$DAEMON_PID_FILE"
    echo -e "${GREEN}✓ Docker auto-update daemon started (PID: $DAEMON_PID)${NC}"
    echo -e "${GREEN}✓ Monitoring: $WATCH_DIR${NC}"
    echo -e "${GREEN}✓ Logs: $DAEMON_LOG_FILE${NC}"
}

# Function to stop daemon
stop_daemon() {
    if [ ! -f "$DAEMON_PID_FILE" ]; then
        echo -e "${YELLOW}Docker auto-update daemon is not running${NC}"
        return 1
    fi

    PID=$(cat "$DAEMON_PID_FILE")

    if ps -p "$PID" > /dev/null 2>&1; then
        echo -e "${BLUE}Stopping Docker auto-update daemon (PID: $PID)...${NC}"
        kill "$PID"
        rm "$DAEMON_PID_FILE"
        rm -f "$STATE_FILE"

        # Stop Docker containers
        docker-compose --profile dev down

        echo -e "${GREEN}✓ Docker auto-update daemon stopped${NC}"
        log "Daemon stopped"
    else
        echo -e "${YELLOW}Daemon process not found, cleaning up...${NC}"
        rm "$DAEMON_PID_FILE"
        rm -f "$STATE_FILE"
    fi
}

# Function to check status
check_status() {
    if [ -f "$DAEMON_PID_FILE" ]; then
        PID=$(cat "$DAEMON_PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            echo -e "${GREEN}✓ Docker auto-update daemon is running${NC}"
            echo -e "  PID: $PID"

            if [ -f "$STATE_FILE" ]; then
                echo -e "  State file: $STATE_FILE"
                cat "$STATE_FILE" | python3 -m json.tool 2>/dev/null || cat "$STATE_FILE"
            fi

            echo -e "\n${BLUE}Recent logs:${NC}"
            tail -n 10 "$DAEMON_LOG_FILE" 2>/dev/null || echo "  No logs available"

            echo -e "\n${BLUE}Docker status:${NC}"
            docker-compose --profile dev ps
        else
            echo -e "${YELLOW}⚠ Daemon PID file exists but process is not running${NC}"
            echo -e "  Run '/docker-auto cleanup' to fix this"
        fi
    else
        echo -e "${RED}✗ Docker auto-update daemon is not running${NC}"
    fi
}

# Function to cleanup
cleanup() {
    echo -e "${BLUE}Cleaning up...${NC}"
    rm -f "$DAEMON_PID_FILE"
    rm -f "$UPDATE_TRIGGER_FILE"
    rm -f "$STATE_FILE"
    echo -e "${GREEN}✓ Cleanup complete${NC}"
}

# Function to show configuration
show_config() {
    echo -e "${BLUE}Docker Auto-Update Configuration:${NC}"
    echo "================================="
    echo "Watch Directory: $WATCH_DIR"
    echo "PID File: $DAEMON_PID_FILE"
    echo "Log File: $DAEMON_LOG_FILE"
    echo "State File: $STATE_FILE"
    echo ""
    echo "Watch Patterns:"
    echo "  - *.tsx, *.ts (Hot reload)"
    echo "  - *.jsx, *.js (Hot reload)"
    echo "  - *.css, *.scss (Hot reload)"
    echo "  - package.json (Rebuild)"
    echo "  - Dockerfile* (Rebuild)"
    echo "  - .env* (Restart)"
}

# Main command handler
case "${1:-status}" in
    start)
        start_daemon
        ;;
    stop)
        stop_daemon
        ;;
    restart)
        stop_daemon
        sleep 2
        start_daemon
        ;;
    status)
        check_status
        ;;
    config)
        show_config
        ;;
    cleanup)
        cleanup
        ;;
    logs)
        echo -e "${BLUE}Docker Auto-Update Daemon Logs:${NC}"
        tail -f "$DAEMON_LOG_FILE"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status|config|cleanup|logs}"
        exit 1
        ;;
esac