#!/bin/bash

# Smooth Schedule - Multi-Tenant SaaS Platform Setup Script
# This script initializes a production-grade Django project with strict multi-tenancy

set -e  # Exit on any error

echo "=================================================="
echo "Smooth Schedule - Project Initialization"
echo "=================================================="

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

# Check if cookiecutter is installed
if ! command -v cookiecutter &> /dev/null; then
    echo -e "${RED}Error: cookiecutter is not installed${NC}"
    echo "Install it with: pip install cookiecutter"
    exit 1
fi

# Project configuration
PROJECT_NAME="Smooth Schedule"
PROJECT_SLUG="smoothschedule"
AUTHOR_NAME="Smooth Schedule Team"
EMAIL="admin@smoothschedule.com"
DESCRIPTION="Multi-Tenant SaaS Resource Orchestration Platform"
DOMAIN_NAME="smoothschedule.com"

echo -e "${GREEN}Step 1: Running cookiecutter-django...${NC}"

# Run cookiecutter with non-interactive mode
cookiecutter gh:cookiecutter/cookiecutter-django \
    --no-input \
    project_name="${PROJECT_NAME}" \
    project_slug="${PROJECT_SLUG}" \
    description="${DESCRIPTION}" \
    author_name="${AUTHOR_NAME}" \
    email="${EMAIL}" \
    domain_name="${DOMAIN_NAME}" \
    version="0.1.0" \
    open_source_license="MIT" \
    timezone="UTC" \
    windows="n" \
    use_pycharm="n" \
    use_docker="y" \
    postgresql_version="14" \
    cloud_provider="AWS" \
    mail_service="Mailgun" \
    use_async="n" \
    use_drf="y" \
    frontend_pipeline="None" \
    use_celery="y" \
    use_mailhog="y" \
    use_sentry="y" \
    use_whitenoise="y" \
    use_heroku="n" \
    ci_tool="Github" \
    keep_local_envs_in_vcs="y" \
    debug="n"

cd "${PROJECT_SLUG}"

echo -e "${GREEN}Step 2: Aggressive De-bloating...${NC}"

# Remove templates directory (we're using React frontend)
if [ -d "${PROJECT_SLUG}/templates" ]; then
    echo -e "${YELLOW}Removing templates/ directory...${NC}"
    rm -rf "${PROJECT_SLUG}/templates"
    echo "✓ Removed templates/"
fi

# Remove pages app (standard About/Home views)
if [ -d "${PROJECT_SLUG}/pages" ]; then
    echo -e "${YELLOW}Removing pages app...${NC}"
    rm -rf "${PROJECT_SLUG}/pages"
    echo "✓ Removed pages app"
fi

# Remove allauth account templates (we're using DRF for auth)
if [ -d "${PROJECT_SLUG}/templates/account" ]; then
    echo -e "${YELLOW}Removing allauth account templates...${NC}"
    rm -rf "${PROJECT_SLUG}/templates/account"
    echo "✓ Removed allauth templates"
fi

# Remove contrib directory if it exists (often contains page views)
if [ -d "${PROJECT_SLUG}/contrib" ]; then
    echo -e "${YELLOW}Removing contrib directory...${NC}"
    rm -rf "${PROJECT_SLUG}/contrib"
    echo "✓ Removed contrib/"
fi

# Clean up settings to remove references to deleted apps
echo -e "${YELLOW}Cleaning up settings files...${NC}"

# Remove pages from INSTALLED_APPS in all settings files
for settings_file in config/settings/*.py; do
    if [ -f "$settings_file" ]; then
        sed -i '/pages/d' "$settings_file" 2>/dev/null || true
        sed -i '/contrib/d' "$settings_file" 2>/dev/null || true
    fi
done

# Remove pages URLs if they exist
if [ -f "config/urls.py" ]; then
    sed -i '/pages/d' "config/urls.py" 2>/dev/null || true
fi

echo -e "${GREEN}Step 3: Installing additional dependencies...${NC}"

# Create requirements directory if it doesn't exist
mkdir -p requirements

# Add django-tenants to base requirements
if [ -f "requirements/base.txt" ]; then
    echo "" >> requirements/base.txt
    echo "# Multi-Tenancy" >> requirements/base.txt
    echo "django-tenants==3.5.0" >> requirements/base.txt
    echo "" >> requirements/base.txt
    echo "# Security & Masquerading" >> requirements/base.txt
    echo "django-hijack==3.4.1" >> requirements/base.txt
    echo "✓ Added django-tenants and django-hijack to requirements"
fi

echo -e "${GREEN}Step 4: Creating core application structure...${NC}"

# Create core app
python manage.py startapp core

# Create additional required directories
mkdir -p core/migrations
mkdir -p core/management/commands
mkdir -p logs

# Create __init__.py files
touch core/__init__.py
touch core/management/__init__.py
touch core/management/commands/__init__.py

echo "✓ Created core app structure"

echo -e "${GREEN}Step 5: Verification...${NC}"

# Verify Django Admin is intact
if [ -f "config/urls.py" ]; then
    if grep -q "admin.site.urls" "config/urls.py"; then
        echo "✓ Django Admin is preserved"
    else
        echo -e "${RED}Warning: Django Admin may not be properly configured${NC}"
    fi
fi

# Verify de-bloat
if [ ! -d "${PROJECT_SLUG}/templates" ]; then
    echo "✓ Templates directory removed"
else
    echo -e "${RED}Warning: Templates directory still exists${NC}"
fi

if [ ! -d "${PROJECT_SLUG}/pages" ]; then
    echo "✓ Pages app removed"
else
    echo -e "${RED}Warning: Pages app still exists${NC}"
fi

echo ""
echo "=================================================="
echo -e "${GREEN}Smooth Schedule Project Initialization Complete!${NC}"
echo "=================================================="
echo ""
echo "Next Steps:"
echo "1. cd ${PROJECT_SLUG}"
echo "2. Review the generated settings in config/settings/"
echo "3. Set up your .env file with database credentials"
echo "4. Run: docker-compose build"
echo "5. Run: docker-compose up"
echo ""
echo "Note: Django Admin is accessible at /admin/"
echo "      (This is the only HTML interface allowed)"
echo ""
