#!/bin/bash

# Function to kill background processes on exit
cleanup() {
    echo "Stopping servers..."
    kill $(jobs -p)
    exit
}

trap cleanup SIGINT SIGTERM

echo "Starting Stock Analysis Web App..."

# 1. Start Backend
echo "Starting Backend (Port 8000)..."
if [ -d ".venv" ]; then
    source .venv/bin/activate
fi

# Ensure PYTHONPATH includes current directory so app.main works
export PYTHONPATH=$PYTHONPATH:$(pwd)/backend

# Run uvicorn in background using .venv's Python
.venv/bin/python -m uvicorn backend.app.main:app --reload --port 8000 &
BACKEND_PID=$!

# Wait a moment for backend to initialize
sleep 2

# 2. Start Frontend
echo "Starting Frontend (Port 3000)..."
cd frontend
npm run dev &
FRONTEND_PID=$!

echo "App is running!"
echo "Backend: http://localhost:8000/docs"
echo "Frontend: http://localhost:3000"
echo "Press Ctrl+C to stop both servers."

# Wait for both processes
wait $BACKEND_PID $FRONTEND_PID
