#!/usr/bin/env bash
# GroupChat2 Dev Script (macOS/Linux)
# Runs both server (Rust/Axum) and client (Vite) with unified console output.
# Uses separate ports and database from production so both can run simultaneously.
#
#   Production: server :3001, DB chat.db
#   Development: server :3002, Vite client :3003, DB chat-dev.db
#
# Ctrl+C stops both processes.

set -e

ROOT="$(cd "$(dirname "$0")" && pwd)"

# ─── Dev environment (separate from production) ─────────────────────
DEV_SERVER_PORT=3002
DEV_CLIENT_PORT=3003
DEV_DATABASE="chat-dev.db"

export DATABASE_URL="sqlite:${DEV_DATABASE}?mode=rwc"
export BIND_ADDR="0.0.0.0:${DEV_SERVER_PORT}"
export VITE_PORT="${DEV_CLIENT_PORT}"
export VITE_API_PORT="${DEV_SERVER_PORT}"
export RUST_LOG="${RUST_LOG:-info}"

# Colors
MAGENTA='\033[0;35m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
RED='\033[0;31m'
GRAY='\033[0;90m'
NC='\033[0m'

# Load .env for API keys (shared with production)
if [ -f "$ROOT/server/.env" ]; then
    set -a
    source "$ROOT/server/.env"
    set +a
    # Override DB and port with dev values (in case .env sets them)
    export DATABASE_URL="sqlite:${DEV_DATABASE}?mode=rwc"
    export BIND_ADDR="0.0.0.0:${DEV_SERVER_PORT}"
fi

# Install client deps if needed
if [ ! -d "$ROOT/client/node_modules" ]; then
    echo -e "${CYAN}[dev] Installing client dependencies...${NC}"
    (cd "$ROOT/client" && npm install)
fi

echo ""
echo -e "  ${MAGENTA}GroupChat2 Dev Server${NC}"
echo -e "  ${YELLOW}Server:  http://localhost:${DEV_SERVER_PORT}${NC}  ${GRAY}(DB: ${DEV_DATABASE})${NC}"
echo -e "  ${CYAN}Client:  http://localhost:${DEV_CLIENT_PORT}${NC}"
echo -e "  ${GRAY}Press Ctrl+C to stop both${NC}"
echo ""

# Track child PIDs for cleanup
SERVER_PID=""
CLIENT_PID=""

cleanup() {
    echo ""
    echo -e "${RED}[dev] Shutting down...${NC}"

    # Kill background jobs
    [ -n "$SERVER_PID" ] && kill "$SERVER_PID" 2>/dev/null
    [ -n "$CLIENT_PID" ] && kill "$CLIENT_PID" 2>/dev/null

    # Kill any lingering processes on dev ports
    lsof -ti:${DEV_CLIENT_PORT} 2>/dev/null | xargs kill -9 2>/dev/null || true
    lsof -ti:${DEV_SERVER_PORT} 2>/dev/null | xargs kill -9 2>/dev/null || true

    echo -e "${RED}[dev] Stopped.${NC}"
    exit 0
}

trap cleanup INT TERM

# Start server (Rust/Axum) on dev port with dev database
(cd "$ROOT/server" && cargo run 2>&1 | while IFS= read -r line; do
    [ -n "$line" ] && echo -e "${YELLOW}[server]${NC} $line"
done) &
SERVER_PID=$!

# Start client (Vite) on dev port, proxying to dev server
(cd "$ROOT/client" && npm run dev 2>&1 | while IFS= read -r line; do
    [ -n "$line" ] && echo -e "${CYAN}[client]${NC} $line"
done) &
CLIENT_PID=$!

# Wait for either to exit
wait -n "$SERVER_PID" "$CLIENT_PID" 2>/dev/null
echo -e "${RED}[dev] A process exited unexpectedly.${NC}"
cleanup
