#!/bin/bash

# Enamel Wallet - Development Startup Script
# This script starts both backend and frontend servers

echo "🚀 Starting Enamel Wallet Development Environment..."
echo ""

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Check if .env files exist
if [ ! -f ".env" ]; then
    echo -e "${RED}❌ Frontend .env file not found!${NC}"
    echo "Creating from template..."
    if [ -f "env.example" ]; then
        cp env.example .env
        echo -e "${GREEN}✅ Created .env from env.example${NC}"
        echo "Please update .env with your configuration"
    else
        echo -e "${RED}❌ env.example not found!${NC}"
        exit 1
    fi
fi

if [ ! -f "backend/.env" ]; then
    echo -e "${RED}❌ Backend .env file not found!${NC}"
    echo "Creating from template..."
    if [ -f "backend/.env.example" ]; then
        cp backend/.env.example backend/.env
        echo -e "${GREEN}✅ Created backend/.env from backend/.env.example${NC}"
        echo "Please update backend/.env with your database credentials"
    else
        echo -e "${RED}❌ backend/.env.example not found!${NC}"
        exit 1
    fi
fi

echo ""
echo -e "${BLUE}📋 Configuration Check:${NC}"
echo "  Frontend .env: ✅"
echo "  Backend .env: ✅"
echo ""

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

if [ ! -d "backend/node_modules" ]; then
    echo -e "${BLUE}📦 Installing backend dependencies...${NC}"
    cd backend && npm install && cd ..
fi

echo ""
echo -e "${GREEN}🎯 Starting servers...${NC}"
echo ""
echo -e "${BLUE}Backend will run on:${NC} http://localhost:5000"
echo -e "${BLUE}Frontend will run on:${NC} http://localhost:5173"
echo ""
echo -e "${BLUE}Press Ctrl+C to stop both servers${NC}"
echo ""

# Function to cleanup on exit
cleanup() {
    echo ""
    echo -e "${RED}🛑 Stopping servers...${NC}"
    kill $(jobs -p) 2>/dev/null
    exit 0
}

trap cleanup SIGINT SIGTERM

# Start backend
cd backend
npm run dev > ../backend.log 2>&1 &
BACKEND_PID=$!
cd ..

# Wait a moment for backend to start
sleep 3

# Start frontend
npm run dev > frontend.log 2>&1 &
FRONTEND_PID=$!

# Monitor both processes
echo -e "${GREEN}✅ Servers started!${NC}"
echo ""
echo "📝 Logs are being written to:"
echo "  - backend.log"
echo "  - frontend.log"
echo ""
echo "🌐 Open your browser to: http://localhost:5173"
echo ""

# Keep script running
wait
