#!/bin/bash

# Human Assessment Web Interface Start Script
# This script starts both the backend API and frontend dev server

set -e

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

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

echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}Creative Idea Assessment System${NC}"
echo -e "${GREEN}================================${NC}"
echo

# Find Python with FastAPI (use project venv or system)
VENV_PYTHON="$SCRIPT_DIR/../../backend/venv/bin/python"
if [ -x "$VENV_PYTHON" ]; then
    PYTHON_CMD="$VENV_PYTHON"
    UVICORN_CMD="$SCRIPT_DIR/../../backend/venv/bin/uvicorn"
else
    PYTHON_CMD="python3"
    UVICORN_CMD="uvicorn"
fi

# Check if assessment data exists
if [ ! -f "data/assessment_items.json" ]; then
    echo -e "${YELLOW}Assessment data not found. Running prepare_data.py...${NC}"
    $PYTHON_CMD prepare_data.py
    echo
fi

# Check if node_modules exist in frontend
if [ ! -d "frontend/node_modules" ]; then
    echo -e "${YELLOW}Installing frontend dependencies...${NC}"
    cd frontend
    npm install
    cd ..
    echo
fi

# Function to cleanup background processes on exit
cleanup() {
    echo
    echo -e "${YELLOW}Shutting down...${NC}"
    kill $BACKEND_PID 2>/dev/null || true
    kill $FRONTEND_PID 2>/dev/null || true
    exit 0
}

trap cleanup SIGINT SIGTERM

# Start backend
echo -e "${GREEN}Starting backend API on port 8002...${NC}"
cd backend
$UVICORN_CMD app:app --host 0.0.0.0 --port 8002 --reload &
BACKEND_PID=$!
cd ..

# Wait for backend to start
echo "Waiting for backend to initialize..."
sleep 2

# Check if backend is running
if ! curl -s http://localhost:8002/api/health > /dev/null 2>&1; then
    echo -e "${RED}Backend failed to start. Check for errors above.${NC}"
    kill $BACKEND_PID 2>/dev/null || true
    exit 1
fi
echo -e "${GREEN}Backend is running.${NC}"
echo

# Start frontend
echo -e "${GREEN}Starting frontend on port 5174...${NC}"
cd frontend
npm run dev &
FRONTEND_PID=$!
cd ..

# Wait for frontend to start
sleep 3

echo
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}Assessment system is running!${NC}"
echo -e "${GREEN}================================${NC}"
echo
echo -e "Backend API:  ${YELLOW}http://localhost:8002${NC}"
echo -e "Frontend UI:  ${YELLOW}http://localhost:5174${NC}"
echo
echo -e "Press Ctrl+C to stop all services"
echo

# Wait for any process to exit
wait
