"""
Django settings for backend project - PRODUCTION CONFIGURATION

!!! IMPORTANT SECURITY NOTES !!!
- Never commit this file with real secrets to version control
- Use environment variables for all sensitive values in production
- This file includes secure defaults for production deployment
"""

from pathlib import Path
import os
from datetime import timedelta

# Build paths inside the project
BASE_DIR = Path(__file__).resolve().parent.parent

# =============================================================================
# SECURITY SETTINGS - CRITICAL FOR PRODUCTION
# =============================================================================

# SECRET_KEY - MUST be kept secret and unique per deployment
# In production: use environment variable
SECRET_KEY = os.getenv(
    'DJANGO_SECRET_KEY',
    'django-insecure-change-this-immediately-in-production'  # Fallback - will raise error if not set
)

if 'change-this-immediately' in SECRET_KEY:
    raise ValueError("You MUST set DJANGO_SECRET_KEY environment variable in production!")

# DEBUG - NEVER True in production
DEBUG = False

# ALLOWED_HOSTS - Restrict to your actual domains/IPs
ALLOWED_HOSTS = [
    'api.betheljuniorcampus.com',     # Your API subdomain
    'betheljuniorcampus.co.ke',         # Main domain (if serving frontend here)
    'localhost',                        # Optional: for local testing
    '127.0.0.1',
    'api.betheljuniorcampus.betheljuniorcampus.co.ke'
]

# If you have multiple subdomains or load balancer IPs, add them here
# ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', '').split(',')  # Alternative via env

# Secure headers and protections
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'

# HTTPS settings (enforce in production)
SECURE_SSL_REDIRECT = True  # Redirect HTTP → HTTPS
SESSION_COOKIE_SECURE = True  # Only send session cookie over HTTPS
CSRF_COOKIE_SECURE = True     # Only send CSRF cookie over HTTPS

# HSTS - Tell browsers to always use HTTPS
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

# =============================================================================
# APPLICATION DEFINITION
# =============================================================================

INSTALLED_APPS = [
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third-party apps
    'corsheaders',
    'rest_framework',
    'rest_framework_simplejwt',

    # Your app
    'api.apps.ApiConfig',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # Must be first

    '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',
]

# =============================================================================
# CORS SETTINGS - TIGHTLY CONTROLLED FOR PRODUCTION
# =============================================================================

# NEVER allow all origins in production!
CORS_ALLOW_ALL_ORIGINS = False

# Only allow your actual frontend domain(s)
CORS_ALLOWED_ORIGINS = [
    "https://betheljuniorcampus.co.ke",           # Main frontend
    "https://www.betheljuniorcampus.co.ke",        # With www if used
    # "http://localhost:5173",                    # Remove in prod or keep only for staging
]

# If using credentials (cookies, Authorization headers)
CORS_ALLOW_CREDENTIALS = True

# Optional: Restrict methods and headers
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# =============================================================================
# REST FRAMEWORK & JWT
# =============================================================================

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

# JWT Settings
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
    'AUTH_HEADER_TYPES': ('Bearer',),
}

AUTH_USER_MODEL = 'api.CustomUser'

# =============================================================================
# URLS & TEMPLATES
# =============================================================================

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # Optional: for custom error pages
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'

# =============================================================================
# DATABASE - Use environment variables in production
# =============================================================================

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('POSTGRES_DB', 'hkftrrpf_bethel'),
        'USER': os.getenv('POSTGRES_USER', 'hkftrrpf_postgres'),
        'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'BethelJuniorCampus!2026'),  # MUST be set in env!
        'HOST': os.getenv('POSTGRES_HOST', 'localhost'),
        'PORT': os.getenv('POSTGRES_PORT', '5432'),
    }
}

# =============================================================================
# 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'},
]

# =============================================================================
# INTERNATIONALIZATION
# =============================================================================

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Nairobi'  # Recommended for Kenya
USE_I18N = True
USE_TZ = True

# =============================================================================
# STATIC & MEDIA FILES
# =============================================================================

STATIC_URL = '/static/'
# This tells Django to put files exactly where the server expects them
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Jazzmin Settings for a modern look
JAZZMIN_SETTINGS = {
    "site_title": "Bethel Campus Admin",      # Title on the browser tab
    "site_header": "Bethel Junior Campus",    # Title on the login screen
    "site_brand": "Bethel Admin",            # Title on the top-left sidebar
    "site_logo": "images/school-logo.ico",           # Logo (must be in your static folder)
    "welcome_sign": "Welcome to the Campus Portal",
    "search_model": ["auth.User"],           # Add a global search bar for users
    "show_ui_builder": True,                 # ENABLES THE MODERN CUSTOMIZER
}

# This enables the Dark Mode / Light Mode switch
JAZZMIN_UI_TWEAKS = {
    "theme": "flatly",             # Standard modern theme
    "dark_mode_theme": "darkly",   # Theme used when user switches to Dark Mode
}

# In production, serve static/media via Nginx/web server, not Django

# =============================================================================
# DEFAULT TEMP PASSWORD (for new users)
# =============================================================================

# Use environment variable in production
DEFAULT_TEMP_PASSWORD = os.getenv('DEFAULT_TEMP_PASSWORD', 'Bethel2025!')

# =============================================================================
# LOGGING (Optional but recommended)
# =============================================================================

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR / 'logs' / 'django.log',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

# Create logs directory if it doesn't exist
(BASE_DIR / 'logs').mkdir(exist_ok=True)

