#!/bin/bash

# Dubai Analytics Platform Setup Script
# This script sets up the development environment

set -e

echo "🚀 Setting up Dubai Analytics Platform..."

# 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}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if Python is installed
check_python() {
    if ! command -v python3 &> /dev/null; then
        print_error "Python 3.11+ is required but not installed."
        exit 1
    fi
    
    python_version=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
    if [[ $(echo "$python_version < 3.11" | bc -l) -eq 1 ]]; then
        print_error "Python 3.11+ is required. Current version: $python_version"
        exit 1
    fi
    
    print_status "Python $python_version found ✓"
}

# Check if Node.js is installed
check_node() {
    if ! command -v node &> /dev/null; then
        print_error "Node.js 18+ is required but not installed."
        exit 1
    fi
    
    node_version=$(node -v | cut -d'v' -f2)
    major_version=$(echo $node_version | cut -d'.' -f1)
    if [[ $major_version -lt 18 ]]; then
        print_error "Node.js 18+ is required. Current version: $node_version"
        exit 1
    fi
    
    print_status "Node.js $node_version found ✓"
}

# Check if Docker is installed
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_warning "Docker is not installed. You'll need it for production deployment."
    else
        print_status "Docker found ✓"
    fi
}

# Setup Python environment
setup_python() {
    print_status "Setting up Python environment..."
    
    # Create virtual environment
    if [ ! -d "venv" ]; then
        python3 -m venv venv
        print_status "Virtual environment created"
    fi
    
    # Activate virtual environment
    source venv/bin/activate
    
    # Upgrade pip
    pip install --upgrade pip
    
    # Install requirements
    pip install -r requirements.txt
    
    print_status "Python dependencies installed ✓"
}

# Setup frontend
setup_frontend() {
    print_status "Setting up frontend..."
    
    cd frontend
    
    # Install dependencies
    npm install
    
    cd ..
    
    print_status "Frontend dependencies installed ✓"
}

# Setup environment file
setup_env() {
    print_status "Setting up environment configuration..."
    
    if [ ! -f ".env" ]; then
        cp env.example .env
        print_status "Environment file created from template"
        print_warning "Please edit .env file with your configuration"
    else
        print_status "Environment file already exists"
    fi
}

# Setup database
setup_database() {
    print_status "Setting up database..."
    
    # Check if PostgreSQL is running
    if ! pg_isready -q; then
        print_warning "PostgreSQL is not running. Please start it before running migrations."
        return
    fi
    
    # Activate virtual environment
    source venv/bin/activate
    
    # Run migrations
    python manage.py migrate
    
    print_status "Database migrations completed ✓"
}

# Import sample data
import_data() {
    print_status "Importing sample data..."
    
    # Activate virtual environment
    source venv/bin/activate
    
    # Check if sample data directory exists
    if [ ! -d "sample data" ]; then
        print_warning "Sample data directory not found. Skipping data import."
        return
    fi
    
    # Import CSV data
    python manage.py import_csv_data --data-dir "sample data"
    
    print_status "Sample data imported ✓"
}

# Create superuser
create_superuser() {
    print_status "Creating superuser..."
    
    # Activate virtual environment
    source venv/bin/activate
    
    # Check if superuser already exists
    if python manage.py shell -c "from django.contrib.auth import get_user_model; User = get_user_model(); print('Superuser exists' if User.objects.filter(is_superuser=True).exists() else 'No superuser')" | grep -q "Superuser exists"; then
        print_status "Superuser already exists"
    else
        print_warning "Please create a superuser manually:"
        echo "python manage.py createsuperuser"
    fi
}

# Main setup function
main() {
    echo "=========================================="
    echo "  Dubai Analytics Platform Setup"
    echo "=========================================="
    echo
    
    # Check prerequisites
    check_python
    check_node
    check_docker
    
    echo
    
    # Setup components
    setup_python
    setup_frontend
    setup_env
    setup_database
    import_data
    create_superuser
    
    echo
    echo "=========================================="
    print_status "Setup completed successfully! 🎉"
    echo "=========================================="
    echo
    echo "Next steps:"
    echo "1. Edit .env file with your configuration"
    echo "2. Create a superuser: python manage.py createsuperuser"
    echo "3. Start the backend: python manage.py runserver"
    echo "4. Start the frontend: cd frontend && npm run dev"
    echo
    echo "Access the application:"
    echo "- Backend API: http://localhost:8000"
    echo "- Admin Panel: http://localhost:3000"
    echo "- API Docs: http://localhost:8000/api/docs/"
    echo
}

# Run main function
main "$@"
