#!/bin/bash
# SignSpeak AI - Main Setup Script
# This script sets up the complete development environment

set -e  # Exit on error

echo "🚀 SignSpeak AI - Environment Setup"
echo "=================================="

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}✓${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

# Detect OS
OS="Unknown"
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="Linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macOS"
elif [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then
    OS="Windows"
fi

print_status "Detected OS: $OS"

# Check Python version
PYTHON_VERSION=$(python3 --version 2>&1 | grep -oE '[0-9]+\.[0-9]+' | head -1)
REQUIRED_PYTHON="3.8"

if (( $(echo "$PYTHON_VERSION < $REQUIRED_PYTHON" | bc -l) )); then
    print_error "Python $REQUIRED_PYTHON or higher is required. Found: $PYTHON_VERSION"
    exit 1
fi

print_status "Python version: $PYTHON_VERSION"

# Check Node.js version
if ! command -v node &> /dev/null; then
    print_error "Node.js is not installed. Please install Node.js 16+ from https://nodejs.org/"
    exit 1
fi

NODE_VERSION=$(node --version | grep -oE '[0-9]+' | head -1)
if [ "$NODE_VERSION" -lt 16 ]; then
    print_error "Node.js 16+ is required. Found: v$NODE_VERSION"
    exit 1
fi

print_status "Node.js version: $(node --version)"

# Create .env file if it doesn't exist
if [ ! -f "backend/.env" ]; then
    print_status "Creating backend/.env file..."
    cat > backend/.env << EOL
# SignSpeak AI Environment Variables
# Generated by setup.sh

# API Keys
CEREBRAS_API_KEY=your_cerebras_api_key_here

# Server Configuration
HOST=0.0.0.0
PORT=8000
RELOAD=true

# CORS Settings
CORS_ORIGINS=["http://localhost:3000", "http://localhost:3001"]

# Feature Flags
ENABLE_MOCK_MODE=false
ENABLE_PERFORMANCE_LOGGING=true

# Model Paths
AVATAR_MODEL_PATH=./static/models/avatar-base.glb
GESTURE_ANIMATIONS_PATH=./static/models/gestures/

# WebSocket Settings
WS_HEARTBEAT_INTERVAL=30
WS_MAX_CONNECTIONS=100

# Audio Settings
AUDIO_SAMPLE_RATE=16000
AUDIO_CHANNELS=1

# Video Settings
VIDEO_WIDTH=640
VIDEO_HEIGHT=480
VIDEO_FPS=30
EOL
    print_warning "Please update backend/.env with your Cerebras API key"
else
    print_status "backend/.env already exists"
fi

# Run backend setup
echo -e "\n${GREEN}Setting up Backend...${NC}"
cd backend
bash setup-backend.sh
cd ..

# Run frontend setup
echo -e "\n${GREEN}Setting up Frontend...${NC}"
cd frontend
bash setup-frontend.sh
cd ..

# Create necessary directories
print_status "Creating project directories..."
mkdir -p frontend/public/models/gestures
mkdir -p frontend/public/models/avatar
mkdir -p backend/static/models/gestures
mkdir -p backend/static/mock_data
mkdir -p docs/demo

# Create launch script
print_status "Creating launch script..."
cat > run-dev.sh << 'EOL'
#!/bin/bash
# Development server launcher

echo "🚀 Starting SignSpeak AI Development Servers..."

# Function to kill processes on exit
cleanup() {
    echo -e "\n🛑 Shutting down servers..."
    kill $BACKEND_PID $FRONTEND_PID 2>/dev/null
    exit
}

trap cleanup EXIT INT TERM

# Start backend
echo "Starting backend server..."
cd backend
source venv/bin/activate
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 &
BACKEND_PID=$!
cd ..

# Wait for backend to start
sleep 3

# Start frontend
echo "Starting frontend server..."
cd frontend
npm run dev &
FRONTEND_PID=$!
cd ..

echo -e "\n✅ Servers are running!"
echo "Backend: http://localhost:8000"
echo "Frontend: http://localhost:3000"
echo -e "\nPress Ctrl+C to stop all servers\n"

# Wait for processes
wait
EOL

chmod +x run-dev.sh

# Final summary
echo -e "\n${GREEN}=================================="
echo "✅ Setup Complete!"
echo "==================================${NC}\n"

print_status "Backend URL: http://localhost:8000"
print_status "Frontend URL: http://localhost:3000"

echo -e "\n${YELLOW}Next Steps:${NC}"
echo "1. Update backend/.env with your Cerebras API key"
echo "2. Download avatar from readyplayer.me"
echo "3. Create animations in Mixamo"
echo "4. Run './run-dev.sh' to start development servers"

echo -e "\n${GREEN}Happy coding! 🎉${NC}"
