#!/bin/bash
# ============================================================
# Crypto Mining System — Quick Start Script
# ============================================================
set -e

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
log() { echo -e "${GREEN}[✓]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
err() { echo -e "${RED}[✗]${NC} $1"; exit 1; }
info() { echo -e "${BLUE}[→]${NC} $1"; }

echo ""
echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   Crypto Mining Profitability System     ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# ── Backend ─────────────────────────────────────────────────
info "Setting up backend..."
cd backend

if [ ! -f ".env" ]; then
    cp .env.example .env
    warn ".env created from .env.example — please fill in your API keys!"
fi

if [ ! -d "venv" ]; then
    info "Creating Python virtual environment..."
    python3 -m venv venv
fi

source venv/bin/activate
info "Installing Python dependencies..."
pip install -q -r requirements.txt

log "Backend dependencies installed"

# ── Frontend ────────────────────────────────────────────────
info "Setting up frontend..."
cd ../frontend

if [ ! -d "node_modules" ]; then
    info "Installing Node.js dependencies..."
    npm install --silent
fi

log "Frontend dependencies installed"
cd ..

# ── Database ────────────────────────────────────────────────
echo ""
warn "IMPORTANT: Make sure MySQL is running and your .env credentials are correct"
warn "Run the schema manually if needed:"
warn "  mysql -u root -p < database/schema.sql"
echo ""

# ── Start Services ──────────────────────────────────────────
log "Starting services..."
echo ""

# Start backend in background
cd backend
source venv/bin/activate
info "Starting FastAPI backend on http://localhost:8000"
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload &
BACKEND_PID=$!
cd ..

sleep 2

# Start frontend
cd frontend
info "Starting React frontend on http://localhost:5173"
npm run dev &
FRONTEND_PID=$!
cd ..

echo ""
log "System running!"
echo -e "  Frontend:  ${BLUE}http://localhost:5173${NC}"
echo -e "  Backend:   ${BLUE}http://localhost:8000${NC}"
echo -e "  API Docs:  ${BLUE}http://localhost:8000/docs${NC}"
echo ""
echo "Press Ctrl+C to stop all services"

# Cleanup on exit
trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo 'Services stopped.'" EXIT
wait
