"""
Production settings for HAVEN GRAZURI Advance
Auto-generated by setup.py - DO NOT EDIT MANUALLY
"""
from .settings import *
import os

# Override INSTALLED_APPS to exclude grazuri in production.
# The grazuri app is a legacy data-import compatibility layer whose models
# duplicate table names from the loans app (bureau_records, loan_disbursements,
# loan_fees, loan_guarantors, etc.), causing models.E028 system check errors
# that crash every request. It is only needed locally for one-time data imports.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'users',
    'loans',
    'reports',
    'utils',
    'payments',
    'expenses',
    # 'grazuri' intentionally excluded from production — duplicate db_table conflicts
]
# Security Settings
DEBUG = True
ALLOWED_HOSTS = [
    'uzuriapps.xyz',
    'www.uzuriapps.xyz',
    'grazuri.uzuriapps.xyz',
    'www.grazuri.uzuriapps.xyz',
    'branchbusinessadvance.co.ke',
    'www.branchbusinessadvance.co.ke',
    'localhost',
    '127.0.0.1',
]

# Database Settings - Using existing configuration
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('DB_NAME', 'xygbfpsg_loans'),
        'USER': os.getenv('DB_USER', 'xygbfpsg_graz'),
        'PASSWORD': os.getenv('DB_PASSWORD', "+MvX9&%PV']]pW}"),
        'HOST': os.getenv('DB_HOST', 'localhost'),
        'PORT': os.getenv('DB_PORT', '3306'),
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            'charset': 'utf8mb4',
            'connect_timeout': 60,
            'read_timeout': 60,
            'write_timeout': 60,
        }
    }
}

# Security Settings - Enhanced for production
SECRET_KEY = os.getenv('SECRET_KEY', '(W6B1[bCEAu,1wA[dz7^-prod-key-2024)')

# SSL/HTTPS Settings (conditional based on environment)
USE_HTTPS = os.getenv('USE_HTTPS', 'True').lower() == 'true'
if USE_HTTPS:
    SECURE_SSL_REDIRECT = True
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    SECURE_HSTS_SECONDS = 31536000  # 1 year
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True

# Session Settings - Enhanced security
SESSION_COOKIE_AGE = int(os.getenv('SESSION_TIMEOUT', '3600'))  # 1 hour default
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'

# Static and Media Files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

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

# Email Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.getenv('EMAIL_HOST', 'smtp.branchbusinessadvance.co.ke')
EMAIL_PORT = int(os.getenv('EMAIL_PORT', '587'))
EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS', 'True').lower() == 'true'
EMAIL_HOST_USER = os.getenv('EMAIL_USER', 'support@branchbusinessadvance.co.ke')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_PASSWORD', '')
DEFAULT_FROM_EMAIL = os.getenv('DEFAULT_FROM_EMAIL', 'support@branchbusinessadvance.co.ke')
SERVER_EMAIL = DEFAULT_FROM_EMAIL

# 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

# Cache Settings (using database cache for simplicity)
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'cache_table',
        'TIMEOUT': 300,  # 5 minutes
        'OPTIONS': {
            'MAX_ENTRIES': 1000,
        }
    }
}

# 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.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'django.log'),
            'maxBytes': 1024*1024*5,  # 5MB
            'backupCount': 5,
            'formatter': 'verbose',
        },
        'security_file': {
            'level': 'WARNING',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs', 'security.log'),
            'maxBytes': 1024*1024*5,  # 5MB
            'backupCount': 5,
            'formatter': 'verbose',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.security': {
            'handlers': ['security_file'],
            'level': 'WARNING',
            'propagate': False,
        },
        'branch_system': {
            'handlers': ['file', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

# Performance Settings
USE_ETAGS = True
USE_L10N = True

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

# Custom settings for HAVEN GRAZURI Advance
BRANCH_SETTINGS = {
    'COMPANY_NAME': 'HAVEN GRAZURI Advance',
    'COMPANY_EMAIL': 'support@branchbusinessadvance.co.ke',
    'COMPANY_PHONE': '+254700000000',
    'COMPANY_ADDRESS': 'Nairobi, Kenya',
    'SYSTEM_VERSION': '1.0',
    'MAINTENANCE_MODE': False,
}

# System version & developer branding (subtle — shown in footer/admin only)
SYSTEM_VERSION = '1.0'
SYSTEM_DEVELOPER = 'PhinTech Solutions Company Ltd'

# LipiaOnline Developer Payment Gateway
LIPIA_ONLINE_API_KEY = os.getenv('LIPIA_ONLINE_API_KEY', '')

# Audit Logging
AUDIT_LOG_ENABLED = True
AUDIT_LOG_EXCLUDE_URLS = [
    '/static/',
    '/media/',
    '/favicon.ico',
    '/health/',
]

# Rate Limiting (basic implementation)
RATELIMIT_ENABLE = True
RATELIMIT_USE_CACHE = 'default'

# Backup Settings
BACKUP_ENABLED = os.getenv('BACKUP_ENABLED', 'True').lower() == 'true'
BACKUP_RETENTION_DAYS = int(os.getenv('BACKUP_RETENTION_DAYS', '30'))
