"""
Production settings for Django app deployment
This file contains all production-specific configurations
"""

from .settings import *
import os
from pathlib import Path

# =============================================================================
# BASIC SETTINGS
# =============================================================================

# Debug mode - ALWAYS False in production
DEBUG = False

# Secret key - should be set via environment variable in production
SECRET_KEY = os.environ.get('SECRET_KEY', 'django-insecure-n40e5z&k!n4xlbr9#8n#9(6_(ezlsjpv_(_ny-+vq+ab!2$!9v')
# Force allauth to use HTTPS URLs
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https"


# Allowed hosts - add your domain and server IP
ALLOWED_HOSTS = [
    'tayapromediverse.org',
    'www.tayapromediverse.org',
    '34.208.149.1',  # Your server IP (with dots)
    '34-208-149-1',  # Your server IP (with dashes)
    'localhost',
    '127.0.0.1',
]

# =============================================================================
# DATABASE CONFIGURATION
# =============================================================================

# SQLite database for production (can be changed to PostgreSQL later)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Alternative PostgreSQL configuration (uncomment if using PostgreSQL)
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': os.environ.get('DB_NAME', 'django_production'),
#         'USER': os.environ.get('DB_USER', 'django_user'),
#         'PASSWORD': os.environ.get('DB_PASSWORD', 'your_db_password'),
#         'HOST': os.environ.get('DB_HOST', 'localhost'),
#         'PORT': os.environ.get('DB_PORT', '5432'),
#         'OPTIONS': {
#             'sslmode': 'require',
#         },
#     }
# }

# =============================================================================
# STATIC FILES CONFIGURATION
# =============================================================================

# Static files (CSS, JavaScript, Images)
# STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# STATIC_URL = '/django_app/static/'
# STATIC_URL = '/static/'

STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / "staticfiles"]
# STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')



# Additional locations of static files
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

# Static files finders
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

# =============================================================================
# MEDIA FILES CONFIGURATION
# =============================================================================

# Media files (user uploads)
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
MEDIA_URL = '/django_app/media/'

# =============================================================================
# EMAIL CONFIGURATION
# =============================================================================

# Email backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

# SMTP settings
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

# Email credentials (use environment variables in production)
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', 'tayaprolibrary@gmail.com')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD', 'pyfk vtlx aoid vvzb')
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'TAYAPROMEDIVERSE <noreply@tayapromediverse.org>')

# Email timeout
EMAIL_TIMEOUT = 30

# =============================================================================
# SECURITY SETTINGS
# =============================================================================

# HTTPS settings
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Cookie security
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True

# Session settings
SESSION_COOKIE_AGE = 86400  # 24 hours
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_SAVE_EVERY_REQUEST = True

# CSRF settings
CSRF_COOKIE_SAMESITE = 'Strict'
SESSION_COOKIE_SAMESITE = 'Strict'

# Security headers
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'

# HSTS (HTTP Strict Transport Security)
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

# =============================================================================
# CACHING CONFIGURATION
# =============================================================================

# Simple cache for production (can be upgraded to Redis/Memcached)
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

# Cache timeout
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 600  # 10 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = 'django_production'

# =============================================================================
# LOGGING CONFIGURATION
# =============================================================================

# Logging configuration
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'django_error.log'),
            'formatter': 'verbose',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.request': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

# =============================================================================
# PERFORMANCE SETTINGS
# =============================================================================

# Database connection settings
DATABASES['default']['CONN_MAX_AGE'] = 60

# Template caching
TEMPLATES[0]['OPTIONS']['loaders'] = [
    ('django.template.loaders.cached.Loader', [
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    ]),
]

# =============================================================================
# INTERNATIONALIZATION
# =============================================================================

# Language and timezone
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# =============================================================================
# ADMIN CONFIGURATION
# =============================================================================

# Admin URL
ADMIN_URL = 'admin/'

# =============================================================================
# MIDDLEWARE CONFIGURATION
# =============================================================================

# Production middleware
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'allauth.account.middleware.AccountMiddleware',  # 👈 ADD THIS LINE
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


# =============================================================================
# INSTALLED APPS
# =============================================================================

# Production apps
INSTALLED_APPS = [
    # Default Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # Third-party apps
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',

    # Your local apps
    'users',
]
SITE_ID = 3


# =============================================================================
# TEMPLATE CONFIGURATION
# =============================================================================

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

# =============================================================================
# URL CONFIGURATION
# =============================================================================

# Root URL configuration
ROOT_URLCONF = 'conn_prjct.urls'

# =============================================================================
# WSGI CONFIGURATION
# =============================================================================

# WSGI application
WSGI_APPLICATION = 'conn_prjct.wsgi.application'


SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        },
        'OAUTH_PKCE_ENABLED': True,
    }
}


# =============================================================================
# PASSWORD VALIDATION
# =============================================================================

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

# =============================================================================
# AUTHENTICATION
# =============================================================================

# Authentication backends
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

# Login URLs
LOGIN_URL = '/django_app/login/'
LOGIN_REDIRECT_URL = '/django_app/'
LOGOUT_REDIRECT_URL = '/django_app/login/'

# =============================================================================
# MESSAGES
# =============================================================================

# Message storage
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

# =============================================================================
# FILE UPLOAD
# =============================================================================

# File upload settings
FILE_UPLOAD_MAX_MEMORY_SIZE = 5242880  # 5MB
DATA_UPLOAD_MAX_MEMORY_SIZE = 5242880  # 5MB
FILE_UPLOAD_PERMISSIONS = 0o644

# =============================================================================
# SESSION CONFIGURATION
# =============================================================================

# Session engine
SESSION_ENGINE = 'django.contrib.sessions.backends.db'

# Session cookie name
SESSION_COOKIE_NAME = 'django_sessionid'

# =============================================================================
# CSRF CONFIGURATION
# =============================================================================

# CSRF settings
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'

# =============================================================================
# SECURE SETTINGS
# =============================================================================

# Security settings
SECURE_REFERRER_POLICY = 'same-origin'
SECURE_CROSS_ORIGIN_OPENER_POLICY = 'same-origin'

# =============================================================================
# DEVELOPMENT OVERRIDES
# =============================================================================

# Override development settings
if DEBUG:
    # Development overrides
    ALLOWED_HOSTS = ['*']
    SECURE_SSL_REDIRECT = False
    SESSION_COOKIE_SECURE = False
    CSRF_COOKIE_SECURE = False
    SECURE_HSTS_SECONDS = 0
    SECURE_HSTS_INCLUDE_SUBDOMAINS = False
    SECURE_HSTS_PRELOAD = False

# =============================================================================
# ENVIRONMENT VARIABLES
# =============================================================================

# Load environment variables
try:
    from decouple import config
    # Override settings with environment variables
    SECRET_KEY = config('SECRET_KEY', default=SECRET_KEY)
    DEBUG = config('DEBUG', default=DEBUG, cast=bool)
    ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=','.join(ALLOWED_HOSTS)).split(',')
    EMAIL_HOST_USER = config('EMAIL_HOST_USER', default=EMAIL_HOST_USER)
    EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default=EMAIL_HOST_PASSWORD)
    DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', default=DEFAULT_FROM_EMAIL)
except ImportError:
    # decouple not installed, use default values
    pass

# =============================================================================
# FINAL VALIDATIONc
# =============================================================================

# Ensure required directories exist
os.makedirs(os.path.join(BASE_DIR, 'logs'), exist_ok=True)
os.makedirs(STATIC_ROOT, exist_ok=True)
os.makedirs(MEDIA_ROOT, exist_ok=True)

# Print production settings status
print("✅ Production settings loaded successfully!")
print(f"📁 Static files: {STATIC_ROOT}")
print(f"📁 Media files: {MEDIA_ROOT}")
print(f"🔒 Debug mode: {DEBUG}")
print(f"🌐 Allowed hosts: {ALLOWED_HOSTS}")
print(f"📧 Email from: {DEFAULT_FROM_EMAIL}")