"""
Django settings for picker_project project.

Generated by 'django-admin startproject' using Django 5.2.10.

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/
"""

import os
from pathlib import Path

from dotenv import load_dotenv

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

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 = os.environ.get(
    'DJANGO_SECRET_KEY',
    'django-insecure-v^c$v32!j0exj%8^agk(z=t0vy2c&twsmq%z7o%4#-3zvr1!xu',
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', 'True') == 'True'

ALLOWED_HOSTS = ['*']

# cPanel/Passenger terminates SSL upstream of Django, so without this,
# request.scheme (and anything using request.build_absolute_uri()) reports
# plain http even on the live https:// site. SITE_BASE_URL below (already
# used by market/order_emails.py) is the primary fix for links sent by SMS/
# email; this covers request.scheme itself for anything still reading it
# directly (e.g. secure-cookie/CSRF checks).
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'market',
]

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',
    'accounts.middleware.AdminRedirectMiddleware',
    'accounts.middleware.PolicyAcceptanceMiddleware',
]

ROOT_URLCONF = 'picker_project.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',
                'accounts.context_processors.picker_session',
                'market.context_processors.language_context',
            ],
        },
    },
]

WSGI_APPLICATION = 'picker_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
#
# Django's own bookkeeping (sessions, csrf, Django's admin log) lives in local
# SQLite. All Picker business data (users, profiles, products) lives in
# Supabase Postgres and is accessed via the Supabase REST client (PostgREST
# over HTTPS) — see accounts/supabase_client.py. This avoids direct
# Postgres/psycopg networking entirely, matching the ClanertAir pattern.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

SUPABASE_URL = os.environ.get('SUPABASE_URL')
SUPABASE_ANON_KEY = os.environ.get('SUPABASE_ANON_KEY')

# HERE Technologies — routing/geocoding intelligence layered on top of the
# free OSM/OSRM/Nominatim stack (truck-aware routing, live traffic, and an
# automatic fallback when the public OSRM/Nominatim servers fail). Empty
# means the HERE layer is silently skipped and everything behaves exactly
# as it did before — OSM/OSRM/Nominatim remain fully functional on their own.
HERE_API_KEY = os.environ.get('HERE_API_KEY', '')

# WhatsApp number customers send payment screenshots to (E.164, no '+' or spaces,
# e.g. 255700000000 for a Tanzanian number). Placeholder — replace with the real number.
ADMIN_WHATSAPP_NUMBER = os.environ.get('ADMIN_WHATSAPP_NUMBER', '255700000000')

# Used to build absolute links in SMS/email notifications that don't have a
# request object to hand (background-ish sends, broadcasts, the chat
# checkout flow) — no trailing slash.
SITE_BASE_URL = os.environ.get('SITE_BASE_URL', 'https://pickkermarket.com')

# Real outbound email (Gmail SMTP) — signup verification + order/account
# notifications to customers, pickers, and admin.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', EMAIL_HOST_USER)
ADMIN_NOTIFICATION_EMAIL = os.environ.get('ADMIN_NOTIFICATION_EMAIL', EMAIL_HOST_USER)

# Web push (VAPID) — empty means push is silently skipped everywhere
# (subscribing no-ops, sending no-ops) rather than erroring, same
# fail-safe pattern as HERE_API_KEY above.
VAPID_PRIVATE_KEY = os.environ.get('VAPID_PRIVATE_KEY', '')
VAPID_PUBLIC_KEY = os.environ.get('VAPID_PUBLIC_KEY', '')
VAPID_CLAIMS_EMAIL = os.environ.get('VAPID_CLAIMS_EMAIL', 'mailto:admin@example.com')

# Notify Africa — SMS to customers and pickers alongside the existing email
# notifications (order placed, status changes, new messages). Empty token
# means SMS is silently skipped, same fail-safe pattern as HERE_API_KEY above.
NOTIFY_API_TOKEN = os.environ.get('NOTIFY_API_TOKEN', '')
NOTIFY_BASE_URL = os.environ.get('NOTIFY_BASE_URL', 'https://api.notify.africa')
NOTIFY_SENDER_ID = os.environ.get('NOTIFY_SENDER_ID', '')


# AI assistant — free-tier LLMs, all Llama-family where possible. Groq is
# tried FIRST (fast, generous free tier, handles Swahili well); OpenRouter's
# free models are the backup if every Groq model/key fails.
GROQ_API_KEYS = [
    k.strip() for k in os.environ.get('GROQ_API_KEYS', '').split(',') if k.strip()
]
GROQ_MODELS = [
    m.strip() for m in os.environ.get(
        'GROQ_MODELS',
        'llama-3.3-70b-versatile,llama-3.1-8b-instant,meta-llama/llama-4-scout-17b-16e-instruct',
    ).split(',') if m.strip()
]

OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY')
OPENROUTER_MODELS = [
    m.strip() for m in os.environ.get(
        'OPENROUTER_MODELS',
        'meta-llama/llama-3.3-70b-instruct:free,meta-llama/llama-3.2-3b-instruct:free,'
        'openai/gpt-oss-20b:free,nvidia/nemotron-nano-9b-v2:free',
    ).split(',') if m.strip()
]


# 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 = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'

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'

# In-process cache for rarely-changing Supabase lookups (site/fee settings,
# categories, truck types) that were otherwise re-fetched from Supabase on
# nearly every page load. Short TTL (see callers) plus explicit invalidation
# on save, so admin edits still show up immediately rather than waiting out
# the TTL.
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    }
}

# Auth
LOGIN_URL = 'accounts:login'

# Without this, exceptions logged via logging.getLogger(__name__).exception(...)
# in app code (e.g. a failed email send) have no configured handler and can
# go unnoticed — this makes them always show up in the console/server log.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {'class': 'logging.StreamHandler'},
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
}
