"""
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',
    'accounting',  # Added for Chart of Accounts system
    # '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': 'xygbfpsg_loans',
        'USER': 'xygbfpsg_graz',
        'PASSWORD': 'j.ez-xy6##y.rllB',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            'charset': 'utf8mb4',
            'connect_timeout': 60,
            'read_timeout': 60,
            'write_timeout': 60,
        }
    }
}

# ─── Site URL & SasaPay callback URLs ────────────────────────────────────────
# grazuri.uzuriapps.xyz is the domain that actually serves this Django app.
# uzuriapps.xyz returns 404 for all app paths.
# The old PHP paths (SasaPayIPN.php etc.) are registered in urls.py and
# confirmed working — SasaPay portal must point to these exact URLs.
SITE_URL = os.getenv('SITE_URL', 'https://grazuri.uzuriapps.xyz')

# Explicit callback URLs so there is no ambiguity anywhere in the codebase
SASAPAY_IPN_URL          = f'{SITE_URL}/SasaPayIPN.php'
SASAPAY_STK_CALLBACK_URL = f'{SITE_URL}/application/include/sasapaystkpushprocessor.php'
SASAPAY_DISB_CALLBACK_URL = f'{SITE_URL}/application/include/sasapayfundsdisbursementprocessor.php'
# These numbers receive an SMS whenever a SasaPay payment is dropped (no match,
# no loan, no balance, or processing error).  Add every admin phone that should
# be notified.  Format: list of strings in +254XXXXXXXXX or 07XXXXXXXX format.
ADMIN_ALERT_PHONES = [p.strip() for p in
                      os.getenv('ADMIN_ALERT_PHONES', '').split(',')
                      if p.strip()]
# Fallback: if the env var is not set, alerts go to the company phone.
# Replace the placeholder or set ADMIN_ALERT_PHONES in your .env file:
#   ADMIN_ALERT_PHONES=+254700000001,+254700000002
if not ADMIN_ALERT_PHONES:
    ADMIN_ALERT_PHONES = ['+254700000000']   # ← replace with real admin number

# 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 (DEPRECATED — kept for reference)
LIPIA_ONLINE_API_KEY = os.getenv('LIPIA_ONLINE_API_KEY', '')

# M-Pesa Daraja Direct — Developer Payments (PhinTech Solutions Company Ltd)
# Replaces LipiaOnline. App: Prod-PHINTECH SOLUTIONS-1782745321201
MPESA_DEV_CONSUMER_KEY = os.environ.get('MPESA_DEV_CONSUMER_KEY', os.environ.get('MPESA_CONSUMER_KEY', ''))
MPESA_DEV_CONSUMER_SECRET = os.environ.get('MPESA_DEV_CONSUMER_SECRET', os.environ.get('MPESA_CONSUMER_SECRET', ''))
MPESA_DEV_PASSKEY = os.environ.get('MPESA_DEV_PASSKEY', os.environ.get('MPESA_PASSKEY', ''))
MPESA_DEV_SHORTCODE = os.environ.get('MPESA_DEV_SHORTCODE', os.environ.get('MPESA_SHORTCODE', '4501895'))
MPESA_DEV_ENVIRONMENT = os.environ.get('MPESA_DEV_ENVIRONMENT', os.environ.get('MPESA_ENVIRONMENT', 'production'))
MPESA_DEV_CALLBACK_URL = os.environ.get('MPESA_DEV_CALLBACK_URL', '')

# 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'))

