"""
Django Settings for Online Course Platform
=========================================
Single settings file controlled entirely by environment variables (.env file).

Development  → DEBUG=True  in .env
Production   → DEBUG=False in .env  (on cPanel server)

All secrets, hosts, email credentials, and DB name are read from .env so the
same codebase works in both environments without any code change.
"""
import os
from pathlib import Path
from dotenv import load_dotenv

# ---------------------------------------------------------------------------
# Base directory — the root of the project (one level above config/)
# ---------------------------------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent.parent

# Load .env file from the project root.
# On cPanel, place .env in the same folder as manage.py.
load_dotenv(BASE_DIR / '.env')

# ---------------------------------------------------------------------------
# Security
# ---------------------------------------------------------------------------
# NEVER commit the real SECRET_KEY to version control.
# Generate one at: https://djecrety.ir/
SECRET_KEY = os.environ.get('SECRET_KEY', 'django-insecure-change-this-in-production-abcdef123456')

# Set DEBUG=False in production .env
DEBUG = os.environ.get('DEBUG', 'True') == 'True'

# Add your domain here — e.g. ALLOWED_HOSTS=academy.example.com,www.academy.example.com
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')

# ---------------------------------------------------------------------------
# CSRF trusted origins — required when behind a proxy or on HTTPS
# ---------------------------------------------------------------------------
# Example: CSRF_TRUSTED_ORIGINS=https://academy.example.com
_csrf_raw = os.environ.get('CSRF_TRUSTED_ORIGINS', '')
CSRF_TRUSTED_ORIGINS = [o.strip() for o in _csrf_raw.split(',') if o.strip()]

# ---------------------------------------------------------------------------
# Installed apps
# ---------------------------------------------------------------------------
DJANGO_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

LOCAL_APPS = [
    'apps.accounts.apps.AccountsConfig',
    'apps.courses.apps.CoursesConfig',
    'apps.enrollments.apps.EnrollmentsConfig',
    'apps.dashboard.apps.DashboardConfig',
    'apps.support.apps.SupportConfig',
    'apps.certifications.apps.CertificationsConfig',
    'apps.promotions.apps.PromotionsConfig',
    'apps.mentorship.apps.MentorshipConfig',
    'apps.installer.apps.InstallerConfig',
]

# Django-Q for async certificate PDF/badge jobs (optional — sync fallback if missing)
THIRD_PARTY_APPS = []
try:
    import django_q  # noqa: F401
    THIRD_PARTY_APPS.append('django_q')
except ImportError:
    pass

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

# ---------------------------------------------------------------------------
# Middleware
# ---------------------------------------------------------------------------
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # Force /install/ until storage/installed exists
    'apps.installer.middleware.InstallerMiddleware',
]

# Insert WhiteNoise after SecurityMiddleware when available (cPanel / Passenger)
try:
    import whitenoise  # noqa: F401
    _sec = MIDDLEWARE.index('django.middleware.security.SecurityMiddleware')
    MIDDLEWARE.insert(_sec + 1, 'whitenoise.middleware.WhiteNoiseMiddleware')
except ImportError:
    pass

ROOT_URLCONF = 'config.urls'

# ---------------------------------------------------------------------------
# Templates
# ---------------------------------------------------------------------------
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # Custom: injects sidebar_pending_enrollments count for teachers
                'utils.context_processors.teacher_pending_enrollments',
                # Custom: institute branding, currency, payment settings
                'utils.context_processors.site_settings',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'

# ---------------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------------
# Local MAMP MySQL  → DB_ENGINE=mysql in .env
# cPanel / default  → SQLite (DB_NAME relative to BASE_DIR, e.g. db.sqlite3)
_db_engine = os.environ.get('DB_ENGINE', 'sqlite3').lower()

if _db_engine == 'mysql':
    import pymysql
    pymysql.install_as_MySQLdb()

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ.get('DB_NAME', 'tsndigitalacademy'),
            'USER': os.environ.get('DB_USER', 'root'),
            'PASSWORD': os.environ.get('DB_PASSWORD', 'root'),
            'HOST': os.environ.get('DB_HOST', '127.0.0.1'),
            'PORT': os.environ.get('DB_PORT', '8889'),
            'OPTIONS': {
                'charset': 'utf8mb4',
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            },
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / os.environ.get('DB_NAME', 'db.sqlite3'),
        }
    }

# ---------------------------------------------------------------------------
# Password validation
# ---------------------------------------------------------------------------
AUTH_PASSWORD_VALIDATORS = [
    {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
    {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

# ---------------------------------------------------------------------------
# Internationalisation
# ---------------------------------------------------------------------------
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Karachi'   # Pakistan Standard Time
USE_I18N = True
USE_TZ = True

# ---------------------------------------------------------------------------
# Static files  (CSS / JS / images committed to the repo)
# ---------------------------------------------------------------------------
STATIC_URL = '/static/'
# Source static files (used by runserver and collectstatic)
STATICFILES_DIRS = [BASE_DIR / 'static']
# collectstatic copies everything here; WhiteNoise serves from this folder
STATIC_ROOT = BASE_DIR / 'staticfiles'
# WhiteNoise for Passenger/cPanel; fall back if package not installed yet
try:
    import whitenoise  # noqa: F401
    STORAGES = {
        'default': {
            'BACKEND': 'django.core.files.storage.FileSystemStorage',
        },
        'staticfiles': {
            'BACKEND': 'whitenoise.storage.CompressedStaticFilesStorage',
        },
    }
except ImportError:
    pass

# ---------------------------------------------------------------------------
# Media files  (user-uploaded images, payment proofs, etc.)
# ---------------------------------------------------------------------------
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# On shared hosting, Django can serve /media/ (set False if Apache aliases media/)
SERVE_MEDIA = os.environ.get('SERVE_MEDIA', 'True') == 'True'

# ---------------------------------------------------------------------------
# Custom user model & auth redirects
# ---------------------------------------------------------------------------
AUTH_USER_MODEL = 'accounts.CustomUser'

AUTHENTICATION_BACKENDS = [
    'apps.accounts.backends.EmailOrUsernameModelBackend',
    'django.contrib.auth.backends.ModelBackend',
]

LOGIN_URL           = '/accounts/login/'
LOGIN_REDIRECT_URL  = '/dashboard/'
LOGOUT_REDIRECT_URL = '/accounts/login/'

# ---------------------------------------------------------------------------
# Default primary key type
# ---------------------------------------------------------------------------
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# ---------------------------------------------------------------------------
# Security headers  (only active when DEBUG=False)
# ---------------------------------------------------------------------------
if not DEBUG:
    # Redirect all HTTP → HTTPS
    SECURE_SSL_REDIRECT = True
    # Tell browsers this site should only be accessed via HTTPS (1 year)
    SECURE_HSTS_SECONDS = 31536000
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True
    # Prevent browsers from MIME-sniffing a response away from the declared type
    SECURE_CONTENT_TYPE_NOSNIFF = True
    # Send cookies only over HTTPS
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE    = True

# ---------------------------------------------------------------------------
# Email / SMTP Configuration
# ---------------------------------------------------------------------------
# Development  → emails printed to terminal (console backend)
# Production   → set EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
#
# cPanel typical SMTP values (fill these in your production .env):
#   EMAIL_HOST           = mail.example.com
#   EMAIL_PORT           = 587
#   EMAIL_USE_TLS        = True
#   EMAIL_USE_SSL        = False
#   EMAIL_HOST_USER      = noreply@example.com
#   EMAIL_HOST_PASSWORD  = <cPanel email password>
#   DEFAULT_FROM_EMAIL   = TSN Digital Academy <noreply@example.com>
# ---------------------------------------------------------------------------
EMAIL_BACKEND    = os.environ.get('EMAIL_BACKEND', 'django.core.mail.backends.console.EmailBackend')
EMAIL_HOST       = os.environ.get('EMAIL_HOST', 'localhost')
EMAIL_PORT       = int(os.environ.get('EMAIL_PORT', 587))
EMAIL_USE_TLS    = os.environ.get('EMAIL_USE_TLS', 'True') == 'True'
EMAIL_USE_SSL    = os.environ.get('EMAIL_USE_SSL', 'False') == 'True'
EMAIL_HOST_USER  = os.environ.get('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')
DEFAULT_FROM_EMAIL  = os.environ.get('DEFAULT_FROM_EMAIL', 'TSN Digital Academy <noreply@example.com>')
SERVER_EMAIL        = DEFAULT_FROM_EMAIL   # used by Django for admin error emails

# Password-reset link validity in seconds (default 3 days = 259200)
PASSWORD_RESET_TIMEOUT = int(os.environ.get('PASSWORD_RESET_TIMEOUT', 259200))

# ---------------------------------------------------------------------------
# Django messages → Bootstrap alert classes mapping
# ---------------------------------------------------------------------------
from django.contrib.messages import constants as messages   # noqa: E402
MESSAGE_TAGS = {
    messages.DEBUG:   'secondary',
    messages.INFO:    'info',
    messages.SUCCESS: 'success',
    messages.WARNING: 'warning',
    messages.ERROR:   'danger',
}

# ---------------------------------------------------------------------------
# Logging  (writes errors to a log file in production)
# ---------------------------------------------------------------------------
LOGS_DIR = BASE_DIR / 'logs'
LOGS_DIR.mkdir(exist_ok=True)   # create logs/ folder automatically if absent

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[{asctime}] {levelname} {name}: {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': LOGS_DIR / 'django_errors.log',
            'formatter': 'verbose',
        },
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': 'WARNING',
    },
}

# ---------------------------------------------------------------------------
# Certificate issuance (Part 6)
# ---------------------------------------------------------------------------
# Prefix in certificate numbers, e.g. TSN-SEO-2026-00001 (override via .env)
CERTIFICATE_ORG_CODE = os.environ.get('CERTIFICATE_ORG_CODE', 'TSN')
# Absolute site URL for QR codes on PDFs/badges (optional; falls back to /verify/…)
PUBLIC_SITE_URL = os.environ.get('PUBLIC_SITE_URL', '').rstrip('/')

# Django-Q — ORM broker (no Redis required). Run: python manage.py qcluster
Q_CLUSTER = {
    'name': 'tsn_academy',
    'workers': 2,
    'recycle': 500,
    'timeout': 180,
    'retry': 240,
    'queue_limit': 50,
    'bulk': 5,
    'orm': 'default',
    'catch_up': False,
}
