#!/bin/bash

# Attribute Agent - Start Script
# This script starts both backend and frontend services

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"
PID_FILE="$PROJECT_DIR/.pids"

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

echo -e "${GREEN}Starting Attribute Agent...${NC}"

# Check if already running
if [ -f "$PID_FILE" ]; then
    echo -e "${YELLOW}Services might already be running. Run ./stop.sh first.${NC}"
    exit 1
fi

# Start Backend
echo -e "${GREEN}[1/2] Starting Backend...${NC}"
cd "$BACKEND_DIR"

# Create virtual environment if not exists
if [ ! -d "venv" ]; then
    echo "Creating virtual environment..."
    python3 -m venv venv
fi

# Activate and install dependencies
source venv/bin/activate
pip install -r requirements.txt -q

# Start uvicorn in background
uvicorn app.main:app --host 0.0.0.0 --port 8001 &
BACKEND_PID=$!
echo "Backend PID: $BACKEND_PID"

# Start Frontend
echo -e "${GREEN}[2/2] Starting Frontend...${NC}"
cd "$FRONTEND_DIR"

# Install dependencies if node_modules doesn't exist
if [ ! -d "node_modules" ]; then
    echo "Installing frontend dependencies..."
    npm install
fi

# Start vite dev server in background
npm run dev &
FRONTEND_PID=$!
echo "Frontend PID: $FRONTEND_PID"

# Save PIDs
echo "$BACKEND_PID" > "$PID_FILE"
echo "$FRONTEND_PID" >> "$PID_FILE"

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Attribute Agent is running!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "Backend:  ${YELLOW}http://localhost:8001${NC}"
echo -e "Frontend: ${YELLOW}http://localhost:5173${NC}"
echo -e "API Docs: ${YELLOW}http://localhost:8001/docs${NC}"
echo ""
echo -e "Run ${YELLOW}./stop.sh${NC} to stop all services"
