
"""
Django settings for nexusmart project.
Supports both development and production environments via environment variables.
"""

import pymysql
pymysql.install_as_MySQLdb()
pymysql.version_info = (1, 4, 3, "final", 0)

    
import os
import sys
from decouple import config, Csv
from pathlib import Path

# ============================================================================
# BASE CONFIGURATION
# ============================================================================
BASE_DIR = Path(__file__).resolve().parent.parent

# Environment Detection
ENV = config("ENVIRONMENT", default="development").lower()
DEBUG = config("DEBUG", default=(ENV == "development"), cast=bool)

IS_PRODUCTION = ENV == "production"
IS_DEVELOPMENT = ENV == "development"

# Secret Key
SECRET_KEY = config("DJANGO_SECRET_KEY", default="dev-insecure-key-only-for-development")

# ============================================================================
# ALLOWED HOSTS & SECURITY
# ============================================================================
if IS_PRODUCTION:
    ALLOWED_HOSTS = config("ALLOWED_HOSTS", cast=Csv())
else:
    ALLOWED_HOSTS = ["localhost", "127.0.0.1", "*.local"]

# Security Settings
if IS_PRODUCTION:
    SECURE_HSTS_SECONDS = 31536000  # 1 year
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
else:
    SECURE_HSTS_SECONDS = 0
    SECURE_HSTS_INCLUDE_SUBDOMAINS = False
    SECURE_HSTS_PRELOAD = False
    SECURE_SSL_REDIRECT = False
    SESSION_COOKIE_SECURE = False
    CSRF_COOKIE_SECURE = False

# ============================================================================
# INSTALLED APPS
# ============================================================================
INSTALLED_APPS = [
    # Django
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    "django.contrib.humanize",

    # Third-party
    "maintenance_mode",
    "django_bootstrap5",
    "crispy_forms",
    "crispy_bootstrap5",
    "widget_tweaks",
    "django_htmx",
    "django_ckeditor_5",
    "axes",

    # Authentication & Authorization
    "allauth",
    "allauth.account",
    "allauth.mfa",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.facebook",
    "allauth.socialaccount.providers.google",
    "allauth.socialaccount.providers.github",
    "allauth.socialaccount.providers.twitter",
    "allauth.socialaccount.providers.yahoo",

    # Local Apps
    "shop",
    "users",
]


# ============================================================================
# MIDDLEWARE
# ============================================================================
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "axes.middleware.AxesMiddleware",
    "shop.middleware.VisitTrackerMiddleware",
    "shop.middleware.LanguageCurrencySyncMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "allauth.account.middleware.AccountMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django_htmx.middleware.HtmxMiddleware",
    "maintenance_mode.middleware.MaintenanceModeMiddleware",
]

# ============================================================================
# URL CONFIGURATION
# ============================================================================
ROOT_URLCONF = "nexusmart.urls"
WSGI_APPLICATION = "nexusmart.wsgi.application"

# ============================================================================
# DATABASE CONFIGURATION
# ============================================================================
if IS_PRODUCTION:
    DATABASES = {
        "default": {
            "ENGINE": "mysql.connector.django",
            "NAME": config("PROD_DB_NAME"),
            "USER": config("PROD_DB_USER"),
            "PASSWORD": config("PROD_DB_PASSWORD"),
            "OPTIONS": {
                "init_command": "SET default_storage_engine=INNODB",
            },
            'CONN_MAX_AGE': 300,           # Keep connection alive for 5 minutes
            'ATOMIC_REQUESTS': True,
        }
    }
else:
    # Development: SQLite or local MySQL
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.mysql",
            "NAME": config("DEV_DB_NAME", default="nexusmart_db"),
            "USER": config("DEV_DB_USER", default="root"),
            "PASSWORD": config("DEV_DB_PASSWORD", default=""),
            "HOST": config("DEV_DB_HOST", default="localhost"),
            "PORT": config("DEV_DB_PORT", default="3306"),
            "OPTIONS": {
                "init_command": "SET default_storage_engine=INNODB",
            },
        }
    }


# ============================================================================
# TEMPLATES
# ============================================================================
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",
                "shop.context_processors.product_category",
                "shop.context_processors.cart_count",
                "shop.context_processors.currency",
                "shop.context_processors.language",
                "shop.context_processors.special_discounts",
                "shop.context_processors.banshix_socials",
            ],
            "libraries": {
                "shop_extras": "shop.templatetags.shop_extras",
            },
        },
    },
]


# ============================================================================
# AUTHENTICATION & AUTHORIZATION
# ============================================================================
AUTH_USER_MODEL = "users.CustomUser"

AUTHENTICATION_BACKENDS = [
    # "axes.backends.AxesStandaloneBackend",
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

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",
    },
]

# ============================================================================
# DJANGO-ALLAUTH CONFIGURATION
# ============================================================================
# ALLAUTH_UI_THEME = "dark"
SITE_ID = 1

ACCOUNT_FORMS = {
    "signup": "users.forms.CustomUserCreationForm",
}

ACCOUNT_RATE_LIMITS = {
    # "login_failed": "5/10m",
    # "signup": "3/h",
    # "verify_email": "5/h",
    # "password_reset": "3/h",
    # "password_reset_verify": "5/h",
    # "email_confirmation": "3/h",
    # "social_login": "10/1h",
}

LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
ACCOUNT_SIGNUP_REDIRECT_URL = "/welcome/"
ACCOUNT_LOGIN_METHODS = {"username"}
ACCOUNT_EMAIL_MAX_LENGTH = 255
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_SIGNUP_FIELDS = ["email*", "username*", "password1*", "password2*"]
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
SOCIALACCOUNT_LOGIN_ON_GET = True
SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_EMAIL_AUTHENTICATION = True

# ============================================================================
# MFA CONFIGURATION
# ============================================================================
MFA_FORMS = {
    "authenticate": "allauth.mfa.base.forms.AuthenticateForm",
    "reauthenticate": "allauth.mfa.base.forms.AuthenticateForm",
    "activate_totp": "allauth.mfa.totp.forms.ActivateTOTPForm",
    "deactivate_totp": "allauth.mfa.totp.forms.DeactivateTOTPForm",
    "generate_recovery_codes": "allauth.mfa.recovery_codes.forms.GenerateRecoveryCodesForm",
}

MFA_SUPPORTED_TYPES = ["totp", "webauthn", "recovery_codes"]
MFA_PASSKEY_LOGIN_ENABLED = True
MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = not IS_PRODUCTION

# ============================================================================
# DJANGO-CRISPY-FORMS CONFIGURATION
# ============================================================================
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"


# ============================================================================
# EMAIL CONFIGURATION
# ============================================================================
if IS_PRODUCTION:
    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

    # === Use Hosting Email (Recommended for cPanel) ===
    EMAIL_HOST = config("PROD_EMAIL_HOST", default="mail.banshix.com")   # Change to your domain
    EMAIL_PORT = config("PROD_EMAIL_PORT", default=587, cast=int)
    EMAIL_USE_TLS = config("PROD_EMAIL_USE_TLS", default=True, cast=bool)
    EMAIL_HOST_USER = config("PROD_EMAIL_HOST_USER", default="noreply@banshix.com")
    EMAIL_HOST_PASSWORD = config("PROD_EMAIL_HOST_PASSWORD")
    
    DEFAULT_FROM_EMAIL = config("DEFAULT_FROM_EMAIL", default="noreply@banshix.com")
    SERVER_EMAIL = DEFAULT_FROM_EMAIL

else:
    # Development - Show emails in console
    EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    DEFAULT_FROM_EMAIL = "noreply@banshix.com"


# Optional: Extra settings for reliability on shared hosting
EMAIL_TIMEOUT = 30
EMAIL_USE_LOCALTIME = True


# ============================================================================
# MAINTENANCE MODE
# ============================================================================
MAINTENANCE_MODE = config("MAINTENANCE_MODE", default=False, cast=bool)
MAINTENANCE_MODE_IGNORE_SUPERUSER = True
MAINTENANCE_MODE_TEMPLATE = "errors/503.html"


# ============================================================================
# INTERNATIONALIZATION
# ============================================================================
LANGUAGE_CODE = "en"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
USE_L10N = True

LANGUAGES = [
    ("en", "English"),
    ("de", "Deutsch"),
    ("fr", "Français"),
    ("pt", "Português"),
    ("ka", "Georgian"),
]

LOCALE_PATHS = [
    BASE_DIR / "locale",
]

LANGUAGE_CURRENCY_MAPPING = {
    "en": "USD",
    "de": "EUR",
    "fr": "EUR",
    "es": "EUR",
    "zh": "CNY",
    "ja": "JPY",
    "ka": "GEL",
    "ru": "EUR",
    "ar": "USD",
    "pt": "EUR",
}

# ============================================================================
# STATIC & MEDIA FILES
# ============================================================================
STATIC_URL = "static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = BASE_DIR / "staticfiles"

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

# ============================================================================
# DATABASE DEFAULTS
# ============================================================================
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# ============================================================================
# PAYMENT GATEWAYS
# ============================================================================
PAYSTACK_SECRET_KEY = config("PAYSTACK_SECRET_KEY", default="")
PAYSTACK_PUBLIC_KEY = config("PAYSTACK_PUBLIC_KEY", default="")
PAYSTACK_WEBHOOK_SECRET = config("PAYSTACK_WEBHOOK_SECRET", default="")

FLW_PUBLIC_KEY = config("FLW_PUBLIC_KEY", default="")
FLW_SECRET_KEY = config("FLW_SECRET_KEY", default="")
FLW_ENCRYPTION_KEY = config("FLW_ENCRYPTION_KEY", default="")

XAI_API_KEY = config("XAI_API_KEY", default="")

# ============================================================================
# CURRENCY & PAYMENT CONFIGURATION
# ============================================================================
CURRENCIES = {
    "USD": {"symbol": "$", "rate": 1.00, "name": "United States Dollar"},
    "EUR": {"symbol": "€", "rate": 0.92, "name": "Euro"},
    "GBP": {"symbol": "£", "rate": 0.79, "name": "British Pound Sterling"},
    "GEL": {"symbol": "₾", "rate": 2.68, "name": "Georgian Lari"},
    "CNY": {"symbol": "¥", "rate": 7.25, "name": "Chinese Yuan"},
    "JPY": {"symbol": "¥", "rate": 152.50, "name": "Japanese Yen"},
}

DEFAULT_CURRENCY = "USD"


FLUTTERWAVE_INSTALLMENT_PLANS = {
    "3_months": {
        "plan_code": "159739",
        "name": "3 Months Installment Plan",
        "months": 3,
        "description": "Pay in 3 equal monthly installments",
    },
    "6_Months": {
        "plan_code": "159740",
        "name": "6 Months Installment Plan",
        "months": 6,
        "description": "Pay in 6 equal monthly installments",
    },
    "12_Months": {
        "plan_code": "159741",
        "name": "12 Months Installment Plan",
        "months": 12,
        "description": "Pay in 12 equal monthly installments",
    },
    
}

# ============================================================================
# CKEDITOR 5 CONFIGURATION
# ============================================================================
CUSTOM_COLOR_PALETTE = [
    {"color": "hsl(4, 90%, 58%)", "label": "Red"},
    {"color": "hsl(340, 82%, 52%)", "label": "Pink"},
    {"color": "hsl(291, 64%, 42%)", "label": "Purple"},
    {"color": "hsl(262, 52%, 47%)", "label": "Deep Purple"},
    {"color": "hsl(231, 48%, 48%)", "label": "Indigo"},
    {"color": "hsl(207, 90%, 54%)", "label": "Blue"},
]

# ============================================================================
# LOGGING CONFIGURATION
# ============================================================================
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "{levelname} | {asctime} | {module}.{funcName}:{lineno} | {message}",
            "style": "{",
        },
        "simple": {
            "format": "{levelname} | {message}",
            "style": "{",
        },
    },
    "handlers": {
        "console": {
            "level": "WARNING",
            "class": "logging.StreamHandler",
            "stream": sys.stdout,
            "formatter": "simple",
        },
        "file": {
            "level": "WARNING",
            "class": "logging.handlers.RotatingFileHandler",
            "filename": os.path.join(BASE_DIR, "logs", "django.log"),
            "maxBytes": 5 * 1024 * 1024,  # 10MB
            "backupCount": 5,
            "formatter": "verbose",
            "encoding": "utf-8",
        },
    },
    "loggers": {
        "django": {
            "handlers": ["console", "file"],
            "level": "WARNING",
            "propagate": False,
        },
        "django.request": {
            "handlers": ["console", "file"],
            "level": "WARNING",
            "propagate": False,
        },
        "django.db.backends": {
            "handlers": ["console", "file"],
            "level": "WARNING",
            "propagate": False,
        },
        "shop": {
            "handlers": ["console", "file"],
            "level": "WARNING",
            "propagate": False,
        },
        "": {
            "handlers": ["console", "file"],
            "level": "WARNING",
        },
    },
}