#config/settings/base.py
"""
Bilomi Base Settings
Developed by Andrews Fosuhene
"""
from pathlib import Path
from datetime import timedelta
from decouple import config
from corsheaders.defaults import default_headers

BASE_DIR = Path(__file__).resolve().parent.parent.parent

SECRET_KEY = config("SECRET_KEY", default="django-insecure-dev-key")
DEBUG = config("DEBUG", default=True, cast=bool)

ALLOWED_HOSTS = config(
    "ALLOWED_HOSTS",
    default="localhost,127.0.0.1,.bilomi.local",
    cast=lambda value: [item.strip() for item in value.split(',') if item.strip()],
)

INSTALLED_APPS = [
    'apps.core.admin_config.PremiumAdminConfig',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'corsheaders',
    
    'rest_framework',
    'rest_framework_simplejwt.token_blacklist',
    'django_filters',
    'drf_spectacular',
    
    'apps.core',
    'apps.accounts',
    'apps.governance',
    'apps.activities',
    'apps.finance',
    'apps.reporting',
    'apps.engagement',
    'apps.payments',
]

AUTH_USER_MODEL = "accounts.User"


MIDDLEWARE=[
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    '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'
]


CORS_ALLOWED_ORIGINS = config(
    "CORS_ALLOWED_ORIGINS",
    default="http://localhost:5173,http://127.0.0.1:5173",
    cast=lambda value: [item.strip() for item in value.split(',') if item.strip()],
)

CORS_ALLOW_CREDENTIALS = False
CORS_ALLOW_HEADERS = list(default_headers) + [
    "x-tenant-slug",
]

ROOT_URLCONF = "config.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "config.wsgi.application"
ASGI_APPLICATION = "config.asgi.application"

# DATABASES = {
#     "default": {
#         "ENGINE": "django.db.backends.postgresql",
#         "NAME": config("DB_NAME", default="hsmcamp_26"),
#         "USER": config("DB_USER", default="postgres"),
#         #"PASSWORD": config("DB_PASSWORD", default=""),
#         "PASSWORD": config("DB_PASSWORD", default=None) or "",
#         "HOST": config("DB_HOST", default="localhost"),
#         "PORT": config("DB_PORT", default="5432"),
#     }
# }

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": config("DB_NAME", default="db_hsmalumni_26"),
        "USER": config("DB_USER", default="root"),
        "PASSWORD": "",
        "HOST": config("DB_HOST", default="127.0.0.1"),
        "PORT": config("DB_PORT", default="3306"),
        "OPTIONS": {
            "charset": "utf8mb4",
        },
    }
}

REST_FRAMEWORK = {
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",

    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.BasicAuthentication",
    ),

    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticatedOrReadOnly",
    ),

    "DEFAULT_FILTER_BACKENDS": [
        "django_filters.rest_framework.DjangoFilterBackend",
        "rest_framework.filters.SearchFilter",
        "rest_framework.filters.OrderingFilter",
    ],

    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 10,

    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.UserRateThrottle",
        "rest_framework.throttling.AnonRateThrottle",
    ],

    "DEFAULT_THROTTLE_RATES": {
        "user": "500/day",
        "anon": "50/day",
    },
}

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=7),
    'ROTATE_REFRESH_TOKENS':True,
    'BLACKLIST_AFTER_ROTATION':True
}

AUTHENTICATION_BACKENDS = ["django.contrib.auth.backends.ModelBackend"]


SPECTACULAR_SETTINGS={'TITLE':'Church Alumni & Students API','DESCRIPTION':'MVP API for membership, leadership, campus activities and finance reporting.','VERSION':'1.0.0'}

OTP_TTL_MINUTES=int(config('OTP_TTL_MINUTES','5')); 
OTP_PROVIDER=config('OTP_PROVIDER','console'); 
OTP_DEV_CODE=config('OTP_DEV_CODE','123456')

ARKESEL_API_KEY = config('ARKESEL_API_KEY', default='')
ARKESEL_SENDER_ID = config('ARKESEL_SENDER_ID', default='HSM Alumni')
ARKESEL_SMS_URL = config('ARKESEL_SMS_URL', default='https://sms.arkesel.com/api/v2/sms/send')
ARKESEL_BALANCE_URL = config('ARKESEL_BALANCE_URL', default='https://sms.arkesel.com/api/v2/clients/balance-details')
ARKESEL_TIMEOUT_SECONDS = config('ARKESEL_TIMEOUT_SECONDS', default=10, cast=int)


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",
    },
]

LANGUAGE_CODE = "en-us"
TIME_ZONE = "Africa/Accra"
USE_I18N = True
USE_TZ = True



STATIC_URL = "/static/"

STATICFILES_DIRS = [
    BASE_DIR / "static",
]

STATIC_ROOT = BASE_DIR / "staticfiles"

MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

SPECTACULAR_SETTINGS = {
    "TITLE": "Bilomi API",
    "DESCRIPTION": "Investor-ready API documentation for Bilomi - Bill on Me sponsorship, telecom, wallet, billing, and session APIs.",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
    "SWAGGER_UI_DIST": "SIDECAR",
    "SWAGGER_UI_FAVICON_HREF": "SIDECAR",
    "REDOC_DIST": "SIDECAR",
    "COMPONENT_SPLIT_REQUEST": True,
}


PAYSTACK_SECRET_KEY = config("PAYSTACK_SECRET_KEY", default="")
PAYSTACK_PUBLIC_KEY = config("PAYSTACK_PUBLIC_KEY", default="")
PAYSTACK_CALLBACK_URL = config(
    "PAYSTACK_CALLBACK_URL",
    default="http://localhost:5173/payment-success",
)


# Email - development
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DEFAULT_FROM_EMAIL = "Bilomi <no-reply@bilomi.com>"
FRONTEND_URL = config("FRONTEND_URL", default="http://localhost:5174")
PAYMENT_PROVIDER = config("PAYMENT_PROVIDER", default="mock")
PAYMENT_CALLBACK_URL = config("PAYMENT_CALLBACK_URL", default=f"{FRONTEND_URL}/portal/give")

# Later production SMTP
# EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
# EMAIL_HOST = "smtp.gmail.com"
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True
# EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
# EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")

# SMS placeholder
SMS_PROVIDER = "console"
SMS_SENDER_ID = "Bilomi"

