"""
Django settings for gnx project.

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

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/
"""

from pathlib import Path
import os
import secrets
import warnings
from decouple import config

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


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=True, cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1', cast=lambda v: [s.strip() for s in v.split(',')])


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    # Third party apps
    'rest_framework',
    'corsheaders',
    'django_filters',
    'drf_yasg',
    
    # Local apps
    'home',
    'contact',
    'services',
    'about',
    'career',
    'support',
    'blog',
    'case_studies',
    'policies',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'gnx.middleware.ip_whitelist.IPWhitelistMiddleware',  # Production: Block external access
    'gnx.middleware.admin_ip_restriction.AdminIPRestrictionMiddleware',  # Restrict admin to specific IPs
    'gnx.middleware.api_security.FrontendAPIProxyMiddleware',  # Validate requests from frontend/nginx
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'gnx.middleware.csrf_exempt.CSRFExemptMiddleware',  # Exempt CSRF for public API endpoints
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'gnx.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'gnx.wsgi.application'


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

# Force SQLite - change this to False and set USE_POSTGRESQL=True to use PostgreSQL
FORCE_SQLITE = True  # Set to False to allow PostgreSQL

if not FORCE_SQLITE:
    # PostgreSQL configuration (only if FORCE_SQLITE is False)
    USE_POSTGRESQL = config('USE_POSTGRESQL', default='False', cast=bool)
    DATABASE_URL = config('DATABASE_URL', default='')
    if USE_POSTGRESQL and DATABASE_URL and DATABASE_URL.startswith('postgresql://'):
        import dj_database_url
        DATABASES = {
            'default': dj_database_url.parse(DATABASE_URL, conn_max_age=600)
        }
    else:
        # Fallback to SQLite
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': BASE_DIR / 'db.sqlite3',
            }
        }
else:
    # SQLite configuration (forced)
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }


# 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',
        'OPTIONS': {
            'min_length': 12 if not DEBUG else 8,  # Enterprise-grade in production
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# ============================================================================
# PRODUCTION SECURITY SETTINGS
# Backend accessible ONLY from internal network in production
# ============================================================================

# Security Headers
SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=False, cast=bool)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_HSTS_SECONDS = config('SECURE_HSTS_SECONDS', default=31536000 if not DEBUG else 0, cast=int)
SECURE_HSTS_INCLUDE_SUBDOMAINS = config('SECURE_HSTS_INCLUDE_SUBDOMAINS', default=not DEBUG, cast=bool)
SECURE_HSTS_PRELOAD = config('SECURE_HSTS_PRELOAD', default=not DEBUG, cast=bool)
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'
SECURE_REFERRER_POLICY = 'strict-origin-when-cross-origin'

# Session Security
SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE', default=not DEBUG, cast=bool)
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Strict'
SESSION_COOKIE_AGE = 1209600  # 2 weeks

# CSRF Security
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=not DEBUG, cast=bool)
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SAMESITE = 'Strict'
CSRF_TRUSTED_ORIGINS = config(
    'CSRF_TRUSTED_ORIGINS',
    default='https://gnxsoft.com,https://www.gnxsoft.com',
    cast=lambda v: [s.strip() for s in v.split(',')]
)

# Internal IPs - Backend should only be accessed from these
INTERNAL_IPS = ['127.0.0.1', '::1']

# Custom allowed IPs for IP whitelist middleware (comma-separated)
CUSTOM_ALLOWED_IPS = config('CUSTOM_ALLOWED_IPS', default='', cast=lambda v: [s.strip() for s in v.split(',') if s.strip()])

# Admin IP Restriction - Only these IPs can access Django admin
# Comma-separated list of IP addresses or CIDR networks
ADMIN_ALLOWED_IPS = config('ADMIN_ALLOWED_IPS', default='193.194.155.249', cast=lambda v: [s.strip() for s in v.split(',') if s.strip()])


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

# Media files (User uploads)
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# File upload settings
FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024  # 10MB
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024  # 10MB
FILE_UPLOAD_PERMISSIONS = 0o644

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Django REST Framework Configuration
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',  # Allow public access to read-only endpoints
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
        'rest_framework.filters.OrderingFilter',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ] if DEBUG else [
        'rest_framework.renderers.JSONRenderer',  # Production: JSON only, no browsable API
    ],
    # Rate Limiting (Production)
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
    ] if not DEBUG else [],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/hour',      # Anonymous users
        'user': '1000/hour',     # Authenticated users
        'burst': '60/min',       # Short-term burst
        'sustained': '1000/day', # Long-term sustained
    },
}

# ============================================================================
# API SECURITY CONFIGURATION
# API is only accessible from frontend through nginx reverse proxy
# ============================================================================

# Internal API Key - nginx will add this header to prove request came through proxy
# Auto-generates a secure key if not provided (only in DEBUG mode for development)
# In production, you MUST set INTERNAL_API_KEY in your .env file
_manual_api_key = config('INTERNAL_API_KEY', default='')
if not _manual_api_key:
    if DEBUG:
        # Auto-generate a secure key for development
        _auto_generated_key = secrets.token_urlsafe(32)
        INTERNAL_API_KEY = _auto_generated_key
        warnings.warn(
            f"⚠️  INTERNAL_API_KEY not set. Auto-generated key for development: {_auto_generated_key}\n"
            f"   Add this to your nginx config and .env file for consistency.\n"
            f"   In production, you MUST set INTERNAL_API_KEY explicitly in .env",
            UserWarning
        )
    else:
        # Production requires explicit key
        raise ValueError(
            "INTERNAL_API_KEY must be set in production. "
            "Generate one with: python -c \"import secrets; print(secrets.token_urlsafe(32))\""
        )
else:
    INTERNAL_API_KEY = _manual_api_key

# API security path pattern (default: all /api/ paths)
API_SECURITY_PATH_PATTERN = config('API_SECURITY_PATH_PATTERN', default=r'^/api/')

# Enforce API security even in DEBUG mode (for testing)
ENFORCE_API_SECURITY_IN_DEBUG = config('ENFORCE_API_SECURITY_IN_DEBUG', default=False, cast=bool)

# Allowed referer patterns (regex patterns for referer validation)
ALLOWED_REFERER_PATTERNS = config(
    'ALLOWED_REFERER_PATTERNS',
    default='',
    cast=lambda v: [s.strip() for s in v.split(',') if s.strip()]
)

# ============================================================================
# CORS Configuration - Strict origin validation
# ============================================================================
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # React development server
    "http://127.0.0.1:3000",
    "http://localhost:3001",
    "http://127.0.0.1:3001",
]

# Add production origins if configured (defaults to gnxsoft.com domains)
PRODUCTION_ORIGINS = config(
    'PRODUCTION_ORIGINS',
    default='https://gnxsoft.com,https://www.gnxsoft.com',
    cast=lambda v: [s.strip() for s in v.split(',') if s.strip()]
)
if PRODUCTION_ORIGINS:
    CORS_ALLOWED_ORIGINS.extend(PRODUCTION_ORIGINS)

# Strict CORS configuration - only allow configured origins
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = False  # Never allow all origins, even in development
CORS_ALLOWED_ORIGIN_REGEXES = []  # No regex patterns by default

# CORS allowed methods
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

# CORS allowed headers
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'x-internal-api-key',  # Custom header for nginx validation
]

# Django URL configuration
APPEND_SLASH = True

# Email Configuration
# Always use .env configuration for consistency across dev and production
# Set USE_SMTP_IN_DEV=True in your .env file to test real email sending in development
USE_SMTP_IN_DEV = config('USE_SMTP_IN_DEV', default=False, cast=bool)

# Email addresses - same for dev and production (from .env)
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', default='support@gnxsoft.com')
COMPANY_EMAIL = config('COMPANY_EMAIL', default='support@gnxsoft.com')
SUPPORT_EMAIL = config('SUPPORT_EMAIL', default=COMPANY_EMAIL)

if DEBUG and not USE_SMTP_IN_DEV:
    # Development: Use console backend to print emails to console (no SMTP required)
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
    # Production or Dev with SMTP enabled - use SMTP backend
    EMAIL_HOST = config('EMAIL_HOST', default='mail.gnxsoft.com')
    # Use custom backend for localhost to handle SSL certificate issues
    if EMAIL_HOST in ['localhost', '127.0.0.1', '::1']:
        EMAIL_BACKEND = 'gnx.email_backend.LocalhostSMTPBackend'
    else:
        EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
    EMAIL_PORT = config('EMAIL_PORT', default=587, cast=int)
    EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool)
    EMAIL_USE_SSL = config('EMAIL_USE_SSL', default=False, cast=bool)
    EMAIL_HOST_USER = config('EMAIL_HOST_USER')
    EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')

# Email timeout settings for production
EMAIL_TIMEOUT = config('EMAIL_TIMEOUT', default=30, cast=int)

# Site URL for email links
# Use production URL by default if not in DEBUG mode
SITE_URL = config('SITE_URL', default='https://gnxsoft.com' if not DEBUG else 'http://localhost:3000')

# Email connection settings for production reliability
EMAIL_CONNECTION_TIMEOUT = config('EMAIL_CONNECTION_TIMEOUT', default=10, cast=int)
EMAIL_READ_TIMEOUT = config('EMAIL_READ_TIMEOUT', default=10, cast=int)

# 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': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR / 'logs' / 'django.log',
            'maxBytes': 1024 * 1024 * 15,  # 15MB
            'backupCount': 10,
            'formatter': 'verbose',
        },
        'security_file': {
            'level': 'WARNING',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR / 'logs' / 'security.log',
            'maxBytes': 1024 * 1024 * 15,  # 15MB
            'backupCount': 10,
            'formatter': 'verbose',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.security': {
            'handlers': ['security_file', 'console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'contact': {
            'handlers': ['file', 'console'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

# ============================================================================
# PRODUCTION NOTES
# ============================================================================
# In production:
# 1. Set DEBUG=False in environment
# 2. Backend runs on 127.0.0.1:8000 (internal only)
# 3. Firewall blocks external access to port 8000
# 4. Frontend proxies API calls through Nginx
# 5. IP Whitelist Middleware blocks non-internal IPs
# 6. Rate limiting protects against abuse
# 7. Browsable API disabled (JSON only)
# ============================================================================

