"""
Django settings for core project.
"""
import pymysql
pymysql.install_as_MySQLdb()
import os
import sys
from pathlib import Path

# ============================================================================== 
# 1. CORE SETTINGS
# ============================================================================== 
BASE_DIR = Path(__file__).resolve().parent.parent

# --- Security & Debug ---
# WARNING: Keep SECRET_KEY private and set DEBUG = False in production!
SECRET_KEY = "django-insecure-s8(sn((v@cd(hkk=v5k74em22aug)l!24p**2)&iu3(04pm)xq"
DEBUG = False
# settings.py
# --- Hosts & URLs ---
ALLOWED_HOSTS = ["127.0.0.1", "localhost", "school.mentosh.top", "www.school.mentosh.top"]
ROOT_URLCONF = "core.urls"
WSGI_APPLICATION = "core.wsgi.application"

# --- Site URLs ---
# Used by payment gateways and other services to build full URLs
# NOTE: changed SITE_URL to your live BASE_URL so external gateways receive correct callback URLs
BASE_URL = "https://school.mentosh.top"
SITE_URL = os.getenv("SITE_URL", BASE_URL)

# ============================================================================== 
# 2. APPLICATIONS & MIDDLEWARE
# ============================================================================== 
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.humanize",

    # Third-party apps
    "widget_tweaks",
    "crispy_forms",
    "crispy_bootstrap5",

    # Local apps
    "reportcards.apps.ReportcardsConfig",
    "ui",
    "accounts",
    "content",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # Fast static files
    "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",

    # Custom middleware
    "content.middleware.comms_autosend.CommsAutoSendMiddleware",
    "content.middleware.dues_autoqueue.DuesAutoQueueMiddleware",
]

# ============================================================================== 
# 3. TEMPLATES
# ============================================================================== 
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "content.context_processors.branding",
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "ui.context_processors.footer_settings",
                "ui.context_processors.default_class_id",
                'content.context_processors.branding_context',
            ],
        },
    },
]

# Use cached template loader in production
if not DEBUG:
    TEMPLATES[0]["APP_DIRS"] = False
    TEMPLATES[0]["OPTIONS"]["loaders"] = [
        ("django.template.loaders.cached.Loader", [
            "django.template.loaders.filesystem.Loader",
            "django.template.loaders.app_directories.Loader",
        ])
    ]

# ============================================================================== 
# 4. DATABASE
# ============================================================================== 
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "mentosht_school",
        "USER": "mentosht_school",
        "PASSWORD": "321study_-_net__NuhaD2025!@#",
        "HOST": "localhost",
        "PORT": "3306",
        "CONN_MAX_AGE": 600,
        "OPTIONS": {
            "charset": "utf8mb4",
            "use_unicode": True,
            # Set connection time zone and collation
            "init_command": "SET time_zone = '+06:00', NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'",
        },
    }
}

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# ============================================================================== 
# 5. INTERNATIONALIZATION & TIME
# ============================================================================== 
LANGUAGE_CODE = "en"
LANGUAGES = [
    ("en", "English"),
    ("bn", "বাংলা"),
]
LOCALE_PATHS = [BASE_DIR / "locale"]
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True

# ============================================================================== 
# 6. STATIC & MEDIA FILES
# ============================================================================== 
STATIC_URL = "/static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = BASE_DIR / "staticfiles"

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

STORAGES = {
    "default": {  # FileField/ImageField
        "BACKEND": "django.core.files.storage.FileSystemStorage",
        "OPTIONS": {"location": MEDIA_ROOT, "base_url": MEDIA_URL},
    },
    "staticfiles": {
        "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
    },
}

WHITENOISE_MAX_AGE = 60 * 60 * 24 * 365  # 1 year

# ============================================================================== 
# 7. SECURITY & AUTHENTICATION
# ============================================================================== 

# --- 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"},
]

# --- Auth Model & URLs ---
AUTH_USER_MODEL = "accounts.User"
LOGIN_URL = "/accounts/login/"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

# --- Signup Tokens ---
STAFF_INVITE_TOKEN = os.getenv("STAFF_INVITE_TOKEN", "change-me-please")
TEACHER_SIGNUP_TOKEN = "teacher-token-1@3"
ADMIN_SIGNUP_TOKEN = "admin-token-4%6"

# --- Security Headers & CSRF ---
# For deployment behind a reverse proxy (like Passenger/Apache)
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
USE_X_FORWARDED_HOST = True

CSRF_TRUSTED_ORIGINS = [
    "https://school.mentosh.top",
    "https://www.school.mentosh.top",
    "http://127.0.0.1:8000",
    "http://localhost:8000",
    "https://sandbox.sslcommerz.com",
    "https://securepay.sslcommerz.com"
    
]

# ============================================================================== 
# 8. EMAIL SETTINGS
# ============================================================================== 
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_USE_TLS = False
EMAIL_HOST_USER = "nuhad7july02@gmail.com"
EMAIL_HOST_PASSWORD = "edmkazwssbtgmuof"  # app password, no spaces
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_TIMEOUT = 15

# ============================================================================== 
# 9. PAYMENT GATEWAYS
# ============================================================================== 

# --- SSLCommerz ---
SSLCOMMERZ_SANDBOX = True
SSLCOMMERZ_STORE_ID = 'none6915dea6ad9cc'
SSLCOMMERZ_STORE_PASSWORD = 'none6915dea6ad9cc@ssl'


# --- Stripe ---
STRIPE_PUBLIC_KEY = os.getenv(
    "STRIPE_PUBLIC_KEY",
    "pk_test_51SFc1dDteUxLjZ0nUgi0QbRdpXkWqaiPibKxBNktq6ReHaGMlJ0eJ4I7BeqXdepZbAX946RkOO1zSuIMDaSQ0Gqu00SKKv491w",
)
STRIPE_SECRET_KEY = os.getenv(
    "STRIPE_SECRET_KEY",
    "sk_test_51SFc1dDteUxLjZ0nO4Gnjf6D0ovgYQmaP02Xf7zEilx0MqTgeKka40rK5OM35ebURud0oa08E9Zm0vc4Xilg65UC00p91CfAM4",
)
STRIPE_CURRENCY = "usd"
STRIPE_WEBHOOK_SECRET = (
    "whsec_41ddb0110650bea237393a144a09a711ed5c2bca18257026213d6170fc8363c9"
    if DEBUG else os.getenv("STRIPE_WEBHOOK_SECRET", "")
)

# --- Other Gateways (bKash, PayPal) ---
PAYMENTS = {
    "SITE_ORIGIN": os.getenv("SITE_ORIGIN", "https://your-domain.com"),
    "BKASH_BASE": os.getenv("BKASH_BASE", "https://tokenized.sandbox.bka.sh/v1.2.0-beta"),
    "BKASH_USERNAME": os.getenv("BKASH_USERNAME"),
    "BKASH_PASSWORD": os.getenv("BKASH_PASSWORD"),
    "BKASH_APP_KEY": os.getenv("BKASH_APP_KEY"),
    "BKASH_APP_SECRET": os.getenv("BKASH_APP_SECRET"),
    "PP_CLIENT": os.getenv("PP_CLIENT"),
    "PP_SECRET": os.getenv("PP_SECRET"),
    "PP_BASE": os.getenv("PP_BASE", "https://api-m.sandbox.paypal.com"),
}

# ============================================================================== 
# 10. COMMUNICATIONS (SMS)
# ============================================================================== 
SMS_PROVIDER = "console"  # 'console' safely logs SMS to the terminal/file
SMS_SENDER_ID_DEFAULT = "SCHOME"
SMS_SENDER_ID = "SCHOME"

# --- Generic SMS ---
SMS_GENERIC_BASE_URL = "https://api.example-sms.com/send"
SMS_GENERIC_API_KEY = "your-api-key"

# --- Twilio ---
TWILIO_ACCOUNT_SID = "AC62681e4a9f0907d65eae974abde23f86"
TWILIO_AUTH_TOKEN = "1c321283a2c298e433f57706fbb52b64"
TWILIO_FROM_NUMBER = "+8801976250250"

# --- Outbox Behavior ---
COMMS_MAX_ATTEMPTS = 6
COMMS_BURST_LIMIT_PER_MIN = 60
COMMS_THROTTLE_MINUTES = 0  # No throttle during local testing
EMAIL_AUTO_SEND = True      # Enable auto send by middleware
COMMS_AUTOSEND_EMAIL = True
COMMS_AUTOSEND_SMS = False  # Keep SMS off for now
COMMS_AUTOSEND_MIN_INTERVAL = 60  # Seconds between auto-send checks

# ============================================================================== 
# 11. CUSTOM APP SETTINGS
# ============================================================================== 

# --- Crispy Forms ---
CRISPY_ALLOWED_TEMPLATE_PACKS = ("bootstrap5",)
CRISPY_TEMPLATE_PACK = "bootstrap5"

# --- Accounts App ---
ALLOW_STUDENT_PROFILE_CREATE_ON_SIGNUP = True
SECRET_LOGIN_PREFIX = "x9f83"
SECRET_SIGNUP_PREFIX = "k7p1a"
HONEYPOT_PATH = "admin"

# --- Content App (Roles & Info) ---
ROLE_STUDENT = "student"
ROLE_TEACHER = "teacher"
ROLE_ADMIN = "admin"

INSTITUTION_PHONE = "+880-1976250250"
INSTITUTION_EMAIL = "nuhad7july02@gmail.com"
INSTITUTION_ADDRESS = "123 College Road, Sylhet"

# --- Attendance Settings ---
ATTENDANCE_CLASS_MODEL = "content.AcademicClass"
ATTENDANCE_STUDENT_MODEL = "content.Member"

# --- Dues & Fees Settings ---
DEFAULT_MONTHLY_FEE = 2000
INVOICE_HORIZON_MONTHS = 12
ACADEMIC_YEAR_START_MONTH = 1
DUES_SCAN_INTERVAL_MINUTES = 60
DUES_EMAIL_THROTTLE_MINUTES = 60

# ============================================================================== 
# 12. CACHING & LOGGING
# ============================================================================== 

# --- Caching ---
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "schome-local",
    }
}

# --- Logging ---
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'debug.log'),
            'formatter': 'simple',
        },
    },
    'loggers': {
        'django': {  # Catch Django's internal logs
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True,
        },
        '': {  # Catch logs from your apps (root logger)
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}



SESSION_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SECURE = True

CSRF_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SECURE = True


SECURE_CROSS_ORIGIN_OPENER_POLICY = None
SECURE_CROSS_ORIGIN_EMBEDDER_POLICY = None
SECURE_CROSS_ORIGIN_RESOURCE_POLICY = "cross-origin"

# Make cookie valid across subdomains (www vs non-www)
SESSION_COOKIE_DOMAIN = ".school.mentosh.top"

# Names — optional but helpful to avoid collisions
SESSION_COOKIE_NAME = "sch_sessionid"
CSRF_COOKIE_NAME = "sch_csrftoken"

# Security flags
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = False  # must be readable by JS if you ever use it client-side
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# Already set but re-affirm:
SESSION_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SAMESITE = "None"