"""
Django settings for the Acco project.

Acco — a unified discovery & listing platform for real estate, businesses,
and points of interest.
"""

from pathlib import Path
import os

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

# ------------------------------------------------------------------------
# Core / Security
# ------------------------------------------------------------------------
SECRET_KEY = os.environ.get(
    "ACCO_SECRET_KEY",
    "django-insecure-CHANGE-THIS-KEY-BEFORE-DEPLOYING-TO-PRODUCTION-xyz987",
)

DEBUG = os.environ.get("ACCO_DEBUG", "True") == "True"

ALLOWED_HOSTS = ["*"]  # Tighten this in production (e.g. ["acco.mw", "www.acco.mw"])

CSRF_TRUSTED_ORIGINS = os.environ.get("ACCO_CSRF_TRUSTED_ORIGINS", "").split(",") \
    if os.environ.get("ACCO_CSRF_TRUSTED_ORIGINS") else []

# ------------------------------------------------------------------------
# Applications
# ------------------------------------------------------------------------
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sitemaps",
    "django.contrib.humanize",

    # Third-party
    "django.forms",

    # Local
    "core.apps.CoreConfig",
]

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",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "core.middleware.LastSeenMiddleware",
]

ROOT_URLCONF = "accoproject.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",
                "core.context_processors.site_context",
            ],
        },
    },
]

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

# ------------------------------------------------------------------------
# Database — SQLite
# ------------------------------------------------------------------------
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

# ------------------------------------------------------------------------
# Password validation
# ------------------------------------------------------------------------
AUTH_PASSWORD_VALIDATORS = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 6}},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

# ------------------------------------------------------------------------
# Internationalization — English / Chichewa, MWK primary currency
# ------------------------------------------------------------------------
LANGUAGE_CODE = "en"
TIME_ZONE = "Africa/Blantyre"
USE_I18N = True
USE_TZ = True

LANGUAGES = [
    ("en", "English"),
    ("ny", "Chichewa"),
]
LOCALE_PATHS = [BASE_DIR / "locale"]

ACCO_DEFAULT_CURRENCY = "MWK"
ACCO_SUPPORTED_CURRENCIES = ["MWK", "USD"]

# ------------------------------------------------------------------------
# Static & Media
# ------------------------------------------------------------------------
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"

# ------------------------------------------------------------------------
# Auth
# ------------------------------------------------------------------------
LOGIN_URL = "core:login"
LOGIN_REDIRECT_URL = "core:home"
LOGOUT_REDIRECT_URL = "core:home"

# ------------------------------------------------------------------------
# Messages framework -> Bootstrap alert classes
# ------------------------------------------------------------------------
from django.contrib.messages import constants as messages_constants  # noqa: E402

MESSAGE_TAGS = {
    messages_constants.DEBUG: "secondary",
    messages_constants.INFO: "info",
    messages_constants.SUCCESS: "success",
    messages_constants.WARNING: "warning",
    messages_constants.ERROR: "danger",
}

# ------------------------------------------------------------------------
# File upload limits (keep listings light / low-data friendly)
# ------------------------------------------------------------------------
FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024   # 10MB per file
DATA_UPLOAD_MAX_MEMORY_SIZE = 26 * 1024 * 1024   # allow multi-photo uploads
DATA_UPLOAD_MAX_NUMBER_FIELDS = 5000

ACCO_MIN_LISTING_PHOTOS = 4
ACCO_MAX_LISTING_PHOTOS = 15

ACCO_MIN_EVENT_PHOTOS = 1
ACCO_MAX_EVENT_PHOTOS = 10

# ------------------------------------------------------------------------
# Pagination
# ------------------------------------------------------------------------
ACCO_LISTINGS_PER_PAGE = 12
ACCO_EVENTS_PER_PAGE = 12

# ------------------------------------------------------------------------
# Email (console backend by default — swap for SMTP in production)
# ------------------------------------------------------------------------
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DEFAULT_FROM_EMAIL = "Acco <no-reply@acco.mw>"

# ------------------------------------------------------------------------
# Logging
# ------------------------------------------------------------------------
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "root": {"handlers": ["console"], "level": "INFO"},
    "loggers": {
        "django": {"handlers": ["console"], "level": "INFO", "propagate": False},
        "core": {"handlers": ["console"], "level": "DEBUG", "propagate": False},
    },
}