"""
Django settings for config project.

Generated by 'django-admin startproject' using Django 5.2.

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

import dj_database_url
from django.core.exceptions import ImproperlyConfigured

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# 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(
    'SECRET_KEY',
    'django-insecure-1sr%79$j46b8tn2()7z%&z6fhrdaa0u2^+ic)1p8b!o9zv+n9o',
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', 'False').strip().lower() == 'true'

allowed_hosts_raw = os.environ.get(
    'ALLOWED_HOSTS',
    '.railway.app,skulplus.co.ke,www.skulplus.co.ke,localhost,127.0.0.1'
)
ALLOWED_HOSTS = [h.strip() for h in allowed_hosts_raw.split(',') if h.strip()]

railway_public_domain = os.environ.get('RAILWAY_PUBLIC_DOMAIN', '').strip()
if railway_public_domain and railway_public_domain not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append(railway_public_domain)

render_hostname = os.environ.get('RENDER_EXTERNAL_HOSTNAME', '').strip()
if render_hostname and render_hostname not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append(render_hostname)

csrf_trusted_origins_raw = os.environ.get(
    'CSRF_TRUSTED_ORIGINS',
    'https://skulplus.co.ke,https://www.skulplus.co.ke,https://skulplus.up.railway.app,http://127.0.0.1,http://localhost,https://*.railway.app,https://*.up.railway.app',
).strip()
CSRF_TRUSTED_ORIGINS = [
    origin.strip() for origin in csrf_trusted_origins_raw.split(',') if origin.strip()
]
if railway_public_domain:
    railway_origin = f"https://{railway_public_domain}"
    if railway_origin not in CSRF_TRUSTED_ORIGINS:
        CSRF_TRUSTED_ORIGINS.append(railway_origin)
for host in ALLOWED_HOSTS:
    if host and host != '*' and '*' not in host and '.' in host:
        origin = f"https://{host}"
        if origin not in CSRF_TRUSTED_ORIGINS:
            CSRF_TRUSTED_ORIGINS.append(origin)

CSRF_COOKIE_SECURE = os.environ.get('CSRF_COOKIE_SECURE', str(not DEBUG)).strip().lower() == 'true'
SESSION_COOKIE_SECURE = os.environ.get('SESSION_COOKIE_SECURE', str(not DEBUG)).strip().lower() == 'true'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
USE_X_FORWARDED_HOST = True


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'schools',
    'finance',
    'payroll',
    'academics',


]

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

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.template.context_processors.csrf',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # site logo context (exposes SITE_LOGO_URL, SITE_FAVICON_URL)
                'schools.context_processors.site_logo',
                'schools.context_processors.user_access_flags',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'


DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases

database_url = os.environ.get('DATABASE_URL', '').strip()
mysql_password = (
    os.environ.get('CPANEL_DB_PASSWORD')
    or os.environ.get('MYSQL_PASSWORD')
    or os.environ.get('DB_PASSWORD')
    or ''
).strip()
database_config = {}

if database_url:
    try:
        database_config = dj_database_url.parse(
            database_url,
            conn_max_age=600,
            ssl_require=False,
        )
    except Exception:
        database_config = {}

if database_config.get('ENGINE'):
    DATABASES = {
        'default': database_config
    }
elif mysql_password:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ.get('CPANEL_DB_NAME', 'skulplus_skulplus_db'),
            'USER': os.environ.get('CPANEL_DB_USER', 'skulplus_skulplus_user'),
            'PASSWORD': mysql_password,
            'HOST': os.environ.get('CPANEL_DB_HOST', 'localhost'),
            'PORT': os.environ.get('CPANEL_DB_PORT', '3306'),
        }
    }
elif DEBUG:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
else:
    raise ImproperlyConfigured(
        'Configure DATABASE_URL or CPANEL_DB_PASSWORD for the production database.'
    )



# 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/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Serve project-level static files from BASE_DIR / 'static' during development
STATICFILES_DIRS = [BASE_DIR / 'static']

# After login redirect users to a post-login handler that routes by role
LOGIN_REDIRECT_URL = '/post-login/'
# After logout redirect to landing page
LOGOUT_REDIRECT_URL = '/'

# Media files (user-uploaded)
MEDIA_URL = os.environ.get('MEDIA_URL', '/media/')
media_root_env = os.environ.get('MEDIA_ROOT', '').strip()
MEDIA_ROOT = Path(media_root_env) if media_root_env else BASE_DIR / 'media'

# Cloudinary (Railway production uploads)
cloudinary_url = os.environ.get('CLOUDINARY_URL', '').strip()
if cloudinary_url and not cloudinary_url.startswith('cloudinary://'):
    cloudinary_url = ''
if cloudinary_url:
    INSTALLED_APPS += [
        'cloudinary_storage',
        'cloudinary',
    ]

if cloudinary_url:
    STORAGES = {
        'default': {
            'BACKEND': 'cloudinary_storage.storage.MediaCloudinaryStorage',
        },
        'staticfiles': {
            'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage',
        },
    }
