"""
Django settings for branch_system project.

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

For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""

from pathlib import Path
import os
import pymysql
pymysql.install_as_MySQLdb()
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'

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

# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv(BASE_DIR / '.env')

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-6py4&bop)%1!p%r*@0&jq2hu%u(u55-ylsycnrnie58_)lp*+8'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG= True
ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
    '0.0.0.0',
    'testserver',
    'grazuri.uzuriapps.xyz',
    'www.grazuri.uzuriapps.xyz',
    'havengrazuri.co.ke',
    'www.havengrazuri.co.ke',
]


# Application definition

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',  # Re-enabled for data import and compatibility
]

MIDDLEWARE = [
    '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',
    'utils.middleware.MaintenanceModeMiddleware',
    'utils.middleware.SessionTimeoutMiddleware',
    'utils.middleware.BranchMiddleware',
    'utils.document_branch_middleware.DocumentBranchMiddleware',
]

# Handle broken pipe errors
MIDDLEWARE.append('django.middleware.common.BrokenLinkEmailsMiddleware')

ROOT_URLCONF = 'branch_system.urls'

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',
                'utils.context_processors.branches',  # Add this line
            ],
        },
    },
]

WSGI_APPLICATION = 'branch_system.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('DB_NAME', 'acbptxvs_branch_system'),
        'USER': os.getenv('DB_USER', 'root'),
        'PASSWORD': os.getenv('DB_PASSWORD', 'password'),
        'HOST': os.getenv('DB_HOST', 'localhost'),
        'PORT': os.getenv('DB_PORT', '3306'),
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            'charset': 'utf8mb4',
        },
        'TEST': {
            'NAME': 'test_branch_system',
        }
    }
}

# Use SQLite for testing if running tests
import sys
if 'test' in sys.argv:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': ':memory:',
            'OPTIONS': {
                'timeout': 20,
            }
        }
    }
    
    # Disable migrations for faster tests
    class DisableMigrations:
        def __contains__(self, item):
            return True
        
        def __getitem__(self, item):
            return None
    
    MIGRATION_MODULES = DisableMigrations()

# Custom User Model
AUTH_USER_MODEL = 'users.CustomUser'

# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators

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
# https://docs.djangoproject.com/en/5.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Nairobi'

USE_I18N = True

USE_TZ = False


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

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# HAVEN GRAZURI INVESTMENT LIMITEDColor Palette
BRANCH_COLORS = {
    'primary': '#0A3D62',      # Deep Blue
    'secondary': '#3C9EBD',    # Teal Blue
    'background': '#FFFFFF',   # White
    'success': '#2ECC71',      # Green
    'error': '#E74C3C',        # Red
}

# Email settings (for production)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'havenin2023@gmail.com'  # Haven Grazuri email address
EMAIL_HOST_PASSWORD = 'wbuy xygx gbqa fleu '  # You'll need to generate an App Password
DEFAULT_FROM_EMAIL = 'havenin2023@gmail.com'  # Default from email for Haven Grazuri
ADMIN_EMAIL = 'havenin2023@gmail.com'  # Admin email for Haven Grazuri

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

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

# Session settings
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_AGE = 1209600  # 2 weeks in seconds
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_SECURE = False  # Set to True in production with HTTPS
SESSION_COOKIE_HTTPONLY = True  # Prevent JavaScript access to session cookie

# Add this to your settings.py
PASSWORD_RESET_DOMAIN = 'grazuri.uzuriapps.xyz'

# Haven Grazuri Investment Limited Contact Information
COMPANY_NAME = os.getenv('COMPANY_NAME', 'Haven Grazuri Investment Limited')
SMS_SENDER_ID = os.getenv('SMS_SENDER_ID', 'HavGrazuri')  # SMS sender ID for Africa's Talking
MPESA_SHORTCODE = os.getenv('MPESA_SHORTCODE', '4159523')  # M-Pesa shortcode for Haven Grazuri
COMPANY_PHONE_PRIMARY = os.getenv('COMPANY_PHONE', '+254112941830')  # Primary contact number
COMPANY_PHONE_SECONDARY = ['+254114457516', '+254115451752', '+254758587153']  # Secondary contact numbers
COMPANY_WHATSAPP = os.getenv('COMPANY_WHATSAPP', '+254112941830')  # WhatsApp number
COMPANY_EMAIL = os.getenv('COMPANY_EMAIL', 'havenin2023@gmail.com')  # Company email
COMPANY_ADDRESS = '2nd Floor, Old Jogoo Kimakia Building, Stadium Road\nP.O.BOX 78001-00507\nThika, Kenya'  # Physical address

# -----------------------------------------------------------------------
# Africa's Talking SMS Configuration
# Credentials from old PHP system (notifs/notifs.php)
# -----------------------------------------------------------------------
AT_USERNAME = os.getenv('AT_USERNAME', 'Uzuriapps')
AT_API_KEY = os.getenv(
    'AT_API_KEY',
    'atsk_e810a145ccd3a1089769cd17887da70ae76124ff044fa0ab949429e6b388954e6db55009'
)

# -----------------------------------------------------------------------
# SasaPay Payment Gateway Configuration
# Credentials from old PHP system (application/include/sapapaystkpush.php)
# -----------------------------------------------------------------------
SASAPAY_CLIENT_ID = os.getenv(
    'SASAPAY_CLIENT_ID',
    'e63utew7Vk3RmwKxjuMY3jocycFb5eoMZkzyKrPQ'
)
SASAPAY_CLIENT_SECRET = os.getenv(
    'SASAPAY_CLIENT_SECRET',
    '6ysF7fWBESaCNYfsh4aJOWxijTFx4JFIu5LqGFWnMx7TJxKiwaysaiNwe14Wgj9FupB6fhtRFZUas2geZZLjHwbHiShbX8w5bvWjy061Bq1SHX9EQtsBCtnuTLgaOmDV'
)
SASAPAY_MERCHANT_CODE = os.getenv('SASAPAY_MERCHANT_CODE', '1122')
SASAPAY_NETWORK_CODE = os.getenv('SASAPAY_NETWORK_CODE', '63902')  # 63902 = M-Pesa

# Base URL used to build SasaPay callback URLs
SITE_URL = os.getenv('SITE_URL', 'https://uzuriapps.xyz')

# -----------------------------------------------------------------------
# LipiaOnline Developer Payment Configuration
# PhinTech Solutions Company Ltd — https://lipia-online.codewithriz.com
# API key is loaded from .env — NEVER hardcode it here.
# -----------------------------------------------------------------------
LIPIA_ONLINE_API_KEY = os.getenv('LIPIA_ONLINE_API_KEY', '')

# -----------------------------------------------------------------------
# System Version & Branding
# -----------------------------------------------------------------------
SYSTEM_VERSION = '1.0'
SYSTEM_DEVELOPER = 'PhinTech Solutions Company Ltd'

# Import local settings if available (for development overrides)
try:
    from .local_settings import *
except ImportError:
    pass
