#!/usr/bin/env bash
# =============================================================================
# dev-start: Start full development environment
# =============================================================================
# Usage:
#   ./devtools/dev-start           - Start all services
#   ./devtools/dev-start --local   - Use local database (docker-compose)
#   ./devtools/dev-start --prod    - Use production database (SSH tunnel)
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

cd "$PROJECT_DIR"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m'

USE_PROD_DB=true  # Default to prod

# Parse args
while [[ $# -gt 0 ]]; do
    case $1 in
        --local) USE_PROD_DB=false; shift ;;
        --prod)  USE_PROD_DB=true; shift ;;
        *) echo "Unknown option: $1"; exit 1 ;;
    esac
done

echo -e "${CYAN}=== Conversation Assistant Development Environment ===${NC}"

# 1. Check Docker services
echo -e "\n${CYAN}[1/4] Checking Docker services...${NC}"
if docker compose ps --status running 2>/dev/null | grep -q "postgres\|redis"; then
    echo -e "${GREEN}Docker services running${NC}"
else
    echo "Starting Docker services..."
    docker compose up -d
    sleep 2
fi

# 2. Database connection
echo -e "\n${CYAN}[2/4] Setting up database connection...${NC}"
if $USE_PROD_DB; then
    echo "Using production database via SSH tunnel..."
    "$SCRIPT_DIR/prod-tunnel" start

    # Ensure .env points to tunnel
    if ! grep -q "DB_PORT=54333" server/.env 2>/dev/null; then
        echo -e "${YELLOW}Updating server/.env for prod database...${NC}"
        # Fetch credentials if needed
        "$SCRIPT_DIR/prod-tunnel" test >/dev/null 2>&1 || true
    fi
else
    echo "Using local database (docker-compose)..."
    if [[ ! -f server/.env ]] || grep -q "DB_PORT=54333" server/.env; then
        echo -e "${YELLOW}Creating server/.env for local database...${NC}"
        cp server/.env.example server/.env 2>/dev/null || true
    fi
fi

# 3. Start backend
echo -e "\n${CYAN}[3/4] Starting backend server...${NC}"
if lsof -ti :3100 >/dev/null 2>&1; then
    echo -e "${GREEN}Backend already running on port 3100${NC}"
else
    echo "Starting NestJS server..."
    (cd server && pnpm start:dev &)
    sleep 3
    if lsof -ti :3100 >/dev/null 2>&1; then
        echo -e "${GREEN}Backend started${NC}"
    else
        echo -e "${RED}Backend failed to start${NC}"
    fi
fi

# 4. Start frontend
echo -e "\n${CYAN}[4/4] Starting frontend...${NC}"
if lsof -ti :5173 >/dev/null 2>&1; then
    echo -e "${GREEN}Frontend already running on port 5173${NC}"
else
    echo "Starting Vite dev server..."
    (cd frontend && pnpm dev &)
    sleep 2
    if lsof -ti :5173 >/dev/null 2>&1; then
        echo -e "${GREEN}Frontend started${NC}"
    else
        echo -e "${RED}Frontend failed to start${NC}"
    fi
fi

echo -e "\n${CYAN}=== Development Environment Ready ===${NC}"
echo -e "  Frontend:  ${GREEN}http://localhost:5173${NC}"
echo -e "  Backend:   ${GREEN}http://localhost:3100${NC}"
echo -e "  API Docs:  ${GREEN}http://localhost:3100/api/docs${NC}"
echo -e "  Database:  $(if $USE_PROD_DB; then echo "${YELLOW}Production (tunnel)${NC}"; else echo "${GREEN}Local (docker)${NC}"; fi)"
