#!/bin/bash

is_usable_ip() {
    local ip="$1"

    [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || return 1
    [[ "$ip" != "0.0.0.0" ]] || return 1
    [[ "$ip" != 127.* ]] || return 1
    [[ "$ip" != 169.254.* ]] || return 1
    [[ "$ip" != 255.* ]] || return 1
}

list_network_ips() {
    if command -v hostname >/dev/null 2>&1; then
        hostname -I 2>/dev/null | tr ' ' '\n'
    fi

    if command -v ipconfig >/dev/null 2>&1; then
        for interface in en0 en1; do
            ipconfig getifaddr "$interface" 2>/dev/null
        done
    fi

    if command -v ifconfig >/dev/null 2>&1; then
        ifconfig | awk '/inet / {print $2}'
    fi
}

choose_primary_ip() {
    local ip

    for ip in $*; do
        if is_usable_ip "$ip"; then
            echo "$ip"
            return 0
        fi
    done
}

main() {
echo ">>> Pitmaster Production Server"
echo

# Check if PocketBase exists
if [ ! -f "./pocketbase" ]; then
    echo "[ERROR] PocketBase not found. Please ensure pocketbase binary is in the current directory."
    echo "   Download from: https://pocketbase.io/docs/"
    read -p "Press Enter to continue..."
    exit 1
fi

# Check if built frontend exists
if [ ! -d "./pitmaster-ui/dist" ]; then
    echo "[ERROR] Built frontend not found. Please run 'npm run build' in the pitmaster-ui directory first."
    read -p "Press Enter to continue..."
    exit 1
fi

# Check if database exists, if not try to copy from support materials BEFORE starting PocketBase
if [ ! -f "./pb_data/data.db" ]; then
    echo "[WARN] No database found. Checking for support materials..."
    if [ -d "./support-materials/initial_pb_data" ]; then
        echo "[INFO] Found clean database template in support materials."
        echo "   Copying initial database..."
        cp -r "./support-materials/initial_pb_data" "./pb_data"
        if [ -f "./pb_data/data.db" ]; then
            echo "[OK] Database initialized from support materials!"
            echo
        else
            echo "[ERROR] Failed to copy database from support materials."
            echo
        fi
    else
        echo "[WARN] No support materials found. Please ensure you have a database setup."
        echo "   You can still start the server, but you'll need to set up the database manually."
        echo
    fi
fi

echo "[OK] Prerequisites check passed!"
echo

# Check if port 8090 is already in use
echo "[INFO] Checking if port 8090 is available..."
if lsof -Pi :8090 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "[WARN] Port 8090 is already in use!"
    echo "   This might be another instance of Pitmaster or a different application."
    echo "   Please close any other applications using port 8090."
    echo
    echo "   Press Enter to try anyway, or Ctrl+C to cancel..."
    read
fi

echo ">>> Starting production server..."
echo

# Get network IP addresses
echo "[INFO] Detecting network interfaces..."
echo
NETWORK_IPS="$(list_network_ips)"
USABLE_IPS=""

for ip in $NETWORK_IPS; do
    if is_usable_ip "$ip"; then
        echo "   Found IP: $ip"
        USABLE_IPS="$USABLE_IPS $ip"
    fi
done

if [ -z "$USABLE_IPS" ]; then
    echo "   [WARN] No LAN IP address found. Other devices may not be able to connect."
fi

echo
echo "1. Starting PocketBase server with built frontend..."
echo "   Server binding to all interfaces on port 8090"
echo "   This will serve both the API and the React frontend"
echo

# Start PocketBase in background
./pocketbase serve --http=0.0.0.0:8090 --dir=pb_data --publicDir=pitmaster-ui/dist &
POCKETBASE_PID=$!

echo "[OK] Production server started!"
echo

echo "2. Checking for admin users..."
echo "   Waiting for server to be ready..."
sleep 5

# Check if superuser credentials file exists
if [ -f "superuser-credentials.json" ]; then
    echo "[INFO] Superuser credentials file found!"
    echo "   Check superuser-credentials.json for login details."
    echo "   Keep this file secure and delete after first login."
    echo
else
    echo "[INFO] No superuser credentials file found."
    echo "   If this is a new installation, check superuser-credentials.json for login details."
    echo
fi

# Get the primary network IP for display
PRIMARY_IP="$(choose_primary_ip "$USABLE_IPS")"

echo "=== Access your application ==="
echo "   Main App (local): http://localhost:8090"
echo "   PocketBase Admin: http://localhost:8090/_/"
if [ -n "$PRIMARY_IP" ]; then
    echo "   Main App (network): http://$PRIMARY_IP:8090"
    echo "   Admin Login (network): http://$PRIMARY_IP:8090/admin"
else
    echo "   Main App (network): No LAN IP detected"
fi
echo

# Wait a moment for server to start, then open browser
echo "[INFO] Opening browser in 3 seconds..."
sleep 3

# Try to open the network IP first, fallback to localhost
OPEN_URL="http://localhost:8090/admin"
if [ -n "$PRIMARY_IP" ]; then
    OPEN_URL="http://$PRIMARY_IP:8090/admin"
fi

echo "[INFO] Opening browser to $OPEN_URL..."
if command -v xdg-open >/dev/null 2>&1; then
    # Linux
    xdg-open "$OPEN_URL" &
elif command -v open >/dev/null 2>&1; then
    # macOS
    open "$OPEN_URL" &
else
    echo "   Could not automatically open browser. Please manually navigate to:"
    echo "   $OPEN_URL"
fi

echo

echo "Admin Login:"
echo "   Check superuser-credentials.json for login details"
echo "   Keep this file secure and delete after first login"
echo

echo "Useful commands:"
echo "   Stop server: Press Ctrl+C or kill $POCKETBASE_PID"
echo "   View logs: Check the terminal output above"
echo

echo "=== Tips ==="
echo "   - The app is now self-contained and portable"
echo "   - Copy this entire folder to any Linux/Mac machine to run"
echo "   - Make sure the pocketbase binary has execute permissions"
echo "   - Use 'chmod +x pocketbase' if you get permission errors"
echo

echo "Server is running. Press Ctrl+C to stop..."
wait $POCKETBASE_PID

}

if [ "${PITMASTER_SOURCE_ONLY:-0}" != "1" ]; then
    main "$@"
fi
