#!/bin/bash

set -e

echo "Killing existing processes..."
# Kill frontend process (Vite default port)
lsof -t -i:5173 | xargs -r kill -9 || true
# Kill backend process (Uvicorn default port)
lsof -t -i:8000 | xargs -r kill -9 || true
echo "Existing processes killed."

echo "Rebuilding frontend..."
cd frontend
npm install
npm run build
cd ..
echo "Frontend rebuilt."

echo "Rebuilding backend..."
cd backend
pip install -r requirements.txt
cd ..
echo "Backend rebuilt."

echo "Starting backend..."
# Start backend in background, redirecting logs
nohup bash -c "cd backend && uvicorn main:app --host 0.0.0.0 --port 8000 --reload > uvicorn.log 2>&1" &
echo "Backend started. Logs redirected to backend/uvicorn.log"

echo "Starting frontend..."
# Start frontend in background
nohup bash -c "cd frontend && npm run dev" &
echo "Frontend started."

echo "Script finished."