#!/bin/bash

# Configuration
PORT=3005
PID_FILE=".site.pid"
LOG_FILE=".site.log"
BUNDLE_NAME="agentica-website-bundle.zip"

# Function to show usage
usage() {
    echo "Usage: $0 {start|dev|stop|restart|status|bundle}"
    exit 1
}

# Function to start the website
start() {
    MODE=${1:-"dev"}
    if [ "$MODE" == "prod" ]; then
        CMD="npm run start"
        MSG="Starting website in PRODUCTION mode on port $PORT..."
    else
        CMD="npm run dev"
        MSG="Starting website in DEVELOPMENT mode on port $PORT..."
    fi

    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null; then
            echo "Website is already running (PID: $PID) on port $PORT"
            return
        else
            rm "$PID_FILE"
        fi
    fi

    echo "$MSG"
    # Execute command
    nohup $CMD -- -p "$PORT" > "$LOG_FILE" 2>&1 &
    
    PID=$!
    echo "$PID" > "$PID_FILE"
    echo "Website started with PID: $PID"
    echo "Logs are available in $LOG_FILE"
    echo "URL: http://localhost:$PORT"
}

# Function to stop the website
stop() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        echo "Stopping website (PID: $PID)..."
        kill "$PID" 2>/dev/null
        
        # Also kill the child processes (the actual next dev process)
        pkill -P "$PID" 2>/dev/null
        
        rm "$PID_FILE"
        echo "Website stopped."
    else
        echo "Website is not running (no PID file found)."
        # Fallback check for any process running on that port
        PORT_PID=$(lsof -t -i:"$PORT")
        if [ -n "$PORT_PID" ]; then
            echo "Found process $PORT_PID on port $PORT. Killing it..."
            kill -9 "$PORT_PID"
            echo "Process killed."
        fi
    fi
}

# Function to check status
status() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null; then
            echo "Website is RUNNING (PID: $PID) on port $PORT"
        else
            echo "Website is NOT running (stale PID file)."
        fi
    else
        PORT_PID=$(lsof -t -i:"$PORT")
        if [ -n "$PORT_PID" ]; then
            echo "Website is RUNNING on port $PORT (Process: $PORT_PID)"
        else
            echo "Website is NOT running."
        fi
    fi
}

# Function to bundle for deployment (cPanel/Node.js hosting)
bundle() {
    echo "Stage 1: Executing production build..."
    npm run build
    
    if [ $? -ne 0 ]; then
        echo "Critical Error: Production build failed. Aborting bundle."
        exit 1
    fi

    echo "Stage 2: Packaging necessary artifacts into $BUNDLE_NAME..."
    
    # Define necessary files and directories
    # .next: Build output
    # public: Static assets
    # package.json / package-lock.json: Dependencies management
    # *.config.*: Configuration for runtime
    # src: Included for source mapping/runtime debugging if needed (optional, but small)
    TARGETS=".next public package.json package-lock.json next.config.ts postcss.config.mjs tsconfig.json site.sh server.js"
    
    # Use python3 to create the zip since standard 'zip' utility is often missing in minimal shells
    python3 -c "
import zipfile
import os

targets = '$TARGETS'.split()
zip_name = '$BUNDLE_NAME'

print(f'Creating {zip_name}...')
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
    for target in targets:
        if not os.path.exists(target):
            print(f'Warning: {target} not found, skipping...')
            continue
            
        if os.path.isdir(target):
            print(f'Archiving directory: {target}')
            for root, dirs, files in os.walk(target):
                # Skip development and cache artifacts in .next to keep bundle size small
                if target == '.next':
                    parts = root.split(os.sep)
                    if 'dev' in parts or 'cache' in parts:
                        continue
                        
                for file in files:
                    file_path = os.path.join(root, file)
                    zipf.write(file_path, file_path)
        else:
            print(f'Archiving file: {target}')
            zipf.write(target)

print('Bundle creation finalized.')
"
    
    if [ -f "$BUNDLE_NAME" ]; then
        SIZE=$(du -h "$BUNDLE_NAME" | cut -f1)
        echo "Success: $BUNDLE_NAME created successfully ($SIZE)."
        echo "You can now upload this file to your cPanel hosting."
    else
        echo "Error: Failed to create $BUNDLE_NAME."
        exit 1
    fi
}

# Case statement for commands
case "$1" in
    start)
        start "dev"
        ;;
    dev)
        start "dev"
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 2
        start "dev"
        ;;
    status)
        status
        ;;
    bundle)
        bundle
        ;;
    *)
        usage
        ;;
esac
