#!/bin/bash
# ========================================
# Deployment Script for Django ESM Project
# ========================================

set -e  # Exit on error

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

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Django ESM Project - Deployment Script${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# Check if running as root
if [ "$EUID" -eq 0 ]; then 
    echo -e "${RED}Error: Do not run this script as root${NC}"
    exit 1
fi

# Check if in correct directory
if [ ! -f "manage.py" ]; then
    echo -e "${RED}Error: manage.py not found. Run this script from project root.${NC}"
    exit 1
fi

# Function to check command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# ========================================
# 1. Check Prerequisites
# ========================================
echo -e "${YELLOW}[1/8] Checking prerequisites...${NC}"

if ! command_exists python3; then
    echo -e "${RED}Error: Python 3 not installed${NC}"
    exit 1
fi

if ! command_exists pip3; then
    echo -e "${RED}Error: pip3 not installed${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Prerequisites OK${NC}"
echo ""

# ========================================
# 2. Activate Virtual Environment
# ========================================
echo -e "${YELLOW}[2/8] Activating virtual environment...${NC}"

if [ ! -d "venv" ]; then
    echo -e "${YELLOW}Creating virtual environment...${NC}"
    python3 -m venv venv
fi

source venv/bin/activate
echo -e "${GREEN}✓ Virtual environment activated${NC}"
echo ""

# ========================================
# 3. Install Dependencies
# ========================================
echo -e "${YELLOW}[3/8] Installing dependencies...${NC}"

pip install --upgrade pip
pip install -r requirements.txt

# Install production dependencies
pip install gunicorn psycopg2-binary

echo -e "${GREEN}✓ Dependencies installed${NC}"
echo ""

# ========================================
# 4. Check Environment Variables
# ========================================
echo -e "${YELLOW}[4/8] Checking environment configuration...${NC}"

if [ ! -f ".env" ]; then
    echo -e "${YELLOW}Warning: .env file not found${NC}"
    echo -e "${YELLOW}Creating .env from .env.example...${NC}"
    cp .env.example .env
    echo -e "${RED}⚠ Please edit .env with your production values before proceeding${NC}"
    exit 1
fi

# Check DEBUG setting
if grep -q "DEBUG=True" .env; then
    echo -e "${RED}⚠ WARNING: DEBUG=True in .env${NC}"
    echo -e "${RED}   Set DEBUG=False for production!${NC}"
fi

# Check SECRET_KEY
if grep -q "your-secret-key-here" .env; then
    echo -e "${RED}⚠ WARNING: Using default SECRET_KEY${NC}"
    echo -e "${RED}   Generate a new one for production!${NC}"
fi

# Check PayTech configuration
if grep -q "your_paytech_api_key_here" .env; then
    echo -e "${RED}⚠ WARNING: PayTech credentials not configured${NC}"
fi

echo -e "${GREEN}✓ Environment configuration checked${NC}"
echo ""

# ========================================
# 5. Database Migrations
# ========================================
echo -e "${YELLOW}[5/8] Running database migrations...${NC}"

python manage.py makemigrations
python manage.py migrate --no-input

echo -e "${GREEN}✓ Database migrations complete${NC}"
echo ""

# ========================================
# 6. Collect Static Files
# ========================================
echo -e "${YELLOW}[6/8] Collecting static files...${NC}"

python manage.py collectstatic --no-input --clear

echo -e "${GREEN}✓ Static files collected${NC}"
echo ""

# ========================================
# 7. Run Tests (Optional)
# ========================================
echo -e "${YELLOW}[7/8] Running tests...${NC}"

if python manage.py test --no-input; then
    echo -e "${GREEN}✓ All tests passed${NC}"
else
    echo -e "${YELLOW}⚠ Some tests failed (continuing anyway)${NC}"
fi
echo ""

# ========================================
# 8. Check Deployment Readiness
# ========================================
echo -e "${YELLOW}[8/8] Running deployment checks...${NC}"

python manage.py check --deploy 2>&1 | grep -v "?: (security.W" || true

echo -e "${GREEN}✓ Deployment checks complete${NC}"
echo ""

# ========================================
# Summary
# ========================================
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Deployment Preparation Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo ""
echo -e "1. ${YELLOW}Review configuration:${NC}"
echo -e "   - Check .env file"
echo -e "   - Verify DEBUG=False"
echo -e "   - Confirm PayTech credentials"
echo ""
echo -e "2. ${YELLOW}Setup Gunicorn:${NC}"
echo -e "   sudo nano /etc/systemd/system/gunicorn.service"
echo -e "   sudo systemctl start gunicorn"
echo -e "   sudo systemctl enable gunicorn"
echo ""
echo -e "3. ${YELLOW}Configure Nginx:${NC}"
echo -e "   sudo nano /etc/nginx/sites-available/enfantsoleilmonde"
echo -e "   sudo nginx -t"
echo -e "   sudo systemctl reload nginx"
echo ""
echo -e "4. ${YELLOW}Setup SSL:${NC}"
echo -e "   sudo certbot --nginx -d enfantsoleilmonde.org"
echo ""
echo -e "5. ${YELLOW}Create superuser:${NC}"
echo -e "   python manage.py createsuperuser"
echo ""
echo -e "6. ${YELLOW}Test deployment:${NC}"
echo -e "   Visit: https://enfantsoleilmonde.org"
echo -e "   Admin: https://enfantsoleilmonde.org/admin"
echo ""
echo -e "${GREEN}For detailed instructions, see: DEPLOYMENT.md${NC}"
echo ""
