#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════
#  DevOps Portfolio — Deployment Script
#  Usage: ./scripts/deploy.sh [--seed]
# ═══════════════════════════════════════════════════════════════

set -euo pipefail

RESET='\033[0m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
RED='\033[0;31m'

log()     { echo -e "${CYAN}[$(date +%H:%M:%S)]${RESET} $1"; }
success() { echo -e "${GREEN}✓${RESET} $1"; }
warn()    { echo -e "${YELLOW}⚠${RESET}  $1"; }
error()   { echo -e "${RED}✗${RESET} $1"; exit 1; }

SEED_DATA=false
[[ "${1:-}" == "--seed" ]] && SEED_DATA=true

log "Starting deployment..."

# Check .env
if [[ ! -f .env ]]; then
    warn ".env not found. Copying from .env.example..."
    cp .env.example .env
    error "Please fill in .env before continuing."
fi

# Create virtual environment if missing
if [[ ! -d venv ]]; then
    log "Creating virtual environment..."
    python3 -m venv venv
fi

source venv/bin/activate

log "Installing dependencies..."
pip install --upgrade pip -q
pip install -r requirements.txt -q
success "Dependencies installed"

log "Running database migrations..."
python manage.py migrate --noinput
success "Migrations applied"

log "Collecting static files..."
python manage.py collectstatic --noinput -v 0
success "Static files collected"

if $SEED_DATA; then
    log "Seeding sample data..."
    python manage.py seed_data
    success "Sample data seeded"
fi

log "Running Django checks..."
python manage.py check --deploy 2>/dev/null || warn "Some deploy checks failed — review settings"

log "Checking for superuser..."
python manage.py shell -c "
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(is_superuser=True).exists():
    print('NO_SUPERUSER')
" | grep -q "NO_SUPERUSER" && {
    warn "No superuser found!"
    echo -e "${YELLOW}  Run: python manage.py createsuperuser${RESET}"
}

echo ""
echo -e "${GREEN}══════════════════════════════════════════${RESET}"
echo -e "${GREEN}  🚀 Deployment complete!${RESET}"
echo -e "${GREEN}══════════════════════════════════════════${RESET}"
echo ""
echo "  Site:   http://localhost:8000"
echo "  Admin:  http://localhost:8000/admin/"
echo "  API:    http://localhost:8000/api/"
echo ""
echo "  Start server:"
echo "    gunicorn devops_portfolio.wsgi:application --bind 0.0.0.0:8000"
echo "  Or for development:"
echo "    python manage.py runserver"
echo ""
