"""
Django settings for reverse_times project.

Generated by 'django-admin startproject' using Django 4.2.16.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

import os
from pathlib import Path
from dotenv import load_dotenv

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

load_dotenv(os.path.join(BASE_DIR, '.env'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY: DEBUG is OFF unless .env says DEBUG=True (only on your own computer).
DEBUG = os.environ.get('DEBUG', 'False') == 'True'

# SECURITY: the secret key must come from .env on the live server.
SECRET_KEY = os.environ.get('SECRET_KEY', '')
if not SECRET_KEY:
    if not DEBUG:
        from django.core.exceptions import ImproperlyConfigured
        raise ImproperlyConfigured('Set SECRET_KEY in the .env file (see .env.example).')
    SECRET_KEY = 'dev-only-insecure-key-do-not-use-in-production'

# The one official address of the site. Canonical links, sitemaps and structured
# data always use it, so search engines see a single version of every page.
SITE_URL = os.environ.get('SITE_URL', 'https://thereversetimes.com').rstrip('/')
CANONICAL_HOST = SITE_URL.split('://', 1)[-1]

# IndexNow key: lets the site tell Bing (which powers ChatGPT search and Copilot),
# Yandex, Naver and Seznam about new articles within minutes of publishing.
INDEXNOW_KEY = os.environ.get('INDEXNOW_KEY', '9dccbdd4145f4f775b76bfcf572b8622')

allowed_hosts_env = os.environ.get('ALLOWED_HOSTS', 'thereversetimes.com,www.thereversetimes.com,127.0.0.1,localhost')
ALLOWED_HOSTS = [host.strip() for host in allowed_hosts_env.split(',') if host.strip()]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'django.contrib.sitemaps',
    'django.contrib.sites',
    'ckeditor',
    'ckeditor_uploader',
    'taggit',
    'apps.core',
    'apps.articles',
    'apps.submissions',
    'apps.newsletter',
    'apps.store',
    'apps.accounts',
    'apps.engage',
    'apps.games',
]

# Readers sign in with their email OR mobile number (staff can still use their username)
AUTHENTICATION_BACKENDS = [
    'apps.accounts.backends.EmailOrPhoneBackend',
    'django.contrib.auth.backends.ModelBackend',
]

SITE_ID = 1

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'apps.core.middleware.CanonicalHostMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'apps.core.middleware.AdminLoginThrottleMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'reverse_times.urls'

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',
                'apps.core.context_processors.global_settings',
            ],
        },
    },
]

WSGI_APPLICATION = 'reverse_times.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': Path(os.environ.get('SQLITE_PATH', BASE_DIR / 'db.sqlite3')),
        'OPTIONS': {'timeout': 20},  # wait instead of failing when two requests write at once
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Dhaka'  # Bangladesh time for dates shown on the site and in the admin

USE_I18N = True

USE_TZ = True

# Let the site frame its own pages (the admin click map shows a page inside the dashboard).
X_FRAME_OPTIONS = 'SAMEORIGIN'


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Custom Settings for The Reverse Times
MEDIA_URL  = '/media/'
# On cPanel these can point inside public_html (see DEPLOY.md); by default they live next to manage.py.
MEDIA_ROOT = Path(os.environ.get('MEDIA_ROOT', BASE_DIR / 'media'))

STATIC_URL = '/static/'
STATIC_ROOT = Path(os.environ.get('STATIC_ROOT', BASE_DIR / 'staticfiles'))
STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

# Full magazine PDFs (never publicly reachable)
PRIVATE_MEDIA_ROOT = BASE_DIR / 'private_media'

CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_ALLOW_NONIMAGE_FILES = False  # the article editor only accepts pictures
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Custom',
        'toolbar_Custom': [
            ['Bold', 'Italic', 'Underline', 'Strike'],
            ['NumberedList', 'BulletedList', 'Blockquote'],
            ['Link', 'Unlink'],
            ['Image', 'Table'],
            ['Source'],
        ],
        'height': 500,
        'width': '100%',
    }
}

# Email Configuration (Using Gmail SMTP)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

# Gmail address and its App Password come from .env (never write passwords in this file).
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', 'thereversetimer@gmail.com')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', '')

DEFAULT_FROM_EMAIL = f'The Reverse Times <{EMAIL_HOST_USER}>'

# Firebase Authentication — redirect unauthenticated users to homepage
# "Continue with Google": the OAuth Client ID from Google Cloud Console. It is public by design
# (it appears in every page that shows the button). Set GOOGLE_CLIENT_ID in .env to override.
GOOGLE_CLIENT_ID = os.environ.get(
    'GOOGLE_CLIENT_ID', '607934464349-3ka1cj2s09adaco0jcpcnnd24pfqbioh.apps.googleusercontent.com').strip()
# Google's sign-in pop-up must be allowed to talk back to this page.
SECURE_CROSS_ORIGIN_OPENER_POLICY = 'same-origin-allow-popups'

LOGIN_URL = '/account/login/'
LOGIN_REDIRECT_URL = '/account/'
SESSION_COOKIE_AGE = 60 * 60 * 24 * 60  # stay signed in for 60 days

# Telegram Bot Notifications
TELEGRAM_BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN', '')
TELEGRAM_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID', '')


# ─── Live-site security (applies whenever DEBUG is off) ─────────────────────────
CSRF_TRUSTED_ORIGINS = [o.strip() for o in os.environ.get(
    'CSRF_TRUSTED_ORIGINS', 'https://thereversetimes.com,https://www.thereversetimes.com').split(',') if o.strip()]
if not DEBUG:
    SESSION_COOKIE_SECURE = True        # sign-in cookie only travels over HTTPS
    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_HTTPONLY = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_REFERRER_POLICY = 'strict-origin-when-cross-origin'
    # cPanel's Apache handles HTTPS in front of Django. HTTP→HTTPS is forced in .htaccess;
    # Django trusts Apache's "this was HTTPS" header so it builds https:// links.
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    SECURE_SSL_REDIRECT = os.environ.get('SECURE_SSL_REDIRECT', 'False') == 'True'
    # Tell browsers to always use HTTPS. Starts at 1 day; raise to 31536000 once the site has run on HTTPS for a while.
    SECURE_HSTS_SECONDS = int(os.environ.get('SECURE_HSTS_SECONDS', '86400'))
    SECURE_HSTS_INCLUDE_SUBDOMAINS = False
    SECURE_HSTS_PRELOAD = False

# One cache shared by all of the site's worker processes (login limits, rate limits, cached pages).
# Cleared on every update by deploy/update_live.sh.
CACHES = {'default': {
    'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
    'LOCATION': str(BASE_DIR / '.cache'),
    'OPTIONS': {'MAX_ENTRIES': 5000},
}}
if len(__import__('sys').argv) > 1 and __import__('sys').argv[1] == 'test':
    CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}

# Keep uploads sane: a magazine PDF can be big, ordinary form posts cannot.
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024
FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024

# Errors on the live site are logged to logs/django-errors.log (and emailed to ADMINS if set).
ADMINS = [('Site admin', e.strip()) for e in os.environ.get('ADMIN_EMAILS', '').split(',') if e.strip()]
SERVER_EMAIL = DEFAULT_FROM_EMAIL
LOG_DIR = BASE_DIR / 'logs'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {'class': 'logging.StreamHandler'},
        'mail_admins': {'class': 'django.utils.log.AdminEmailHandler', 'level': 'ERROR'},
    },
    'loggers': {'django': {'handlers': ['console', 'mail_admins'], 'level': 'WARNING'}},
}
if not DEBUG:
    try:
        LOG_DIR.mkdir(exist_ok=True)
        LOGGING['handlers']['file'] = {'class': 'logging.FileHandler', 'filename': str(LOG_DIR / 'django-errors.log'),
                                       'level': 'WARNING'}
        LOGGING['loggers']['django']['handlers'].append('file')
    except OSError:
        pass

# Test runs write uploaded files to a throw-away folder, never to the real media/ folder.
import sys as _sys  # noqa: E402
if len(_sys.argv) > 1 and _sys.argv[1] == 'test':
    import tempfile as _tempfile
    MEDIA_ROOT = _tempfile.mkdtemp(prefix='rt-test-media-')
