"""
Django settings for construction_mgmt project.

Construction Partnership & Project Accounting Web App
"""
import os
from pathlib import Path

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

# ------------------------------------------------------------------
# Minimal built-in .env loader (no extra dependency needed).
# Put a .env file next to manage.py (see .env.example) and it will
# be picked up automatically. Real environment variables always win.
# ------------------------------------------------------------------
_env_file = BASE_DIR / ".env"
if _env_file.exists():
    for _line in _env_file.read_text().splitlines():
        _line = _line.strip()
        if not _line or _line.startswith("#") or "=" not in _line:
            continue
        _key, _value = _line.split("=", 1)
        os.environ.setdefault(_key.strip(), _value.strip())

# ============================================================
# SECURITY
# ============================================================

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '')
if not SECRET_KEY:
    raise RuntimeError('DJANGO_SECRET_KEY must be set in .env/environment.')

DEBUG = os.environ.get('DJANGO_DEBUG', 'False').strip().lower() in {'1', 'true', 'yes'}

ALLOWED_HOSTS = [h.strip() for h in os.environ.get('DJANGO_ALLOWED_HOSTS', '127.0.0.1,localhost').split(',') if h.strip()]

# Company database provisioning settings. These are read from the same MySQL
# admin account used by the platform database. The generated company DB
# password is encrypted before it is stored in the application database.
DJANGO_DB_ENGINE = os.environ.get('DJANGO_DB_ENGINE', 'mysql')
DB_NAME = os.environ.get('DB_NAME', 'construction_accounting_db')
DB_USER = os.environ.get('DB_USER', 'root')
DB_PASSWORD = os.environ.get('DB_PASSWORD', '')
DB_HOST = os.environ.get('DB_HOST', '127.0.0.1')
DB_PORT = os.environ.get('DB_PORT', '3306')
TENANT_DB_USER_HOST = os.environ.get('TENANT_DB_USER_HOST', 'localhost')

# Company database passwords are stored in plain text (Project.database_password)
# at the site owner's explicit request — see README.md "Company database
# passwords are stored in plain text" for the reasoning and tradeoffs. No
# encryption key is required for this.


# ============================================================
# APPLICATIONS
# ============================================================

INSTALLED_APPS = [
    # Django built-ins
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',

    # Construction Accounting apps
    'core',
    'accounts',
    'members',
    'contributions',
    'expenses',
    'materials',
    'labor',
    'contractors',
    'flats',
    'sales',
    'finance',
    'reports',
    'dashboard',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',

    # Activates the logged-in user's own company database for this
    # request. Must come after AuthenticationMiddleware (needs
    # request.user) and before any view code runs.
    'core.middleware.TenantRoutingMiddleware',

    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    # Stashes request.user on a thread-local for the audit trail signals
    'core.middleware.CurrentUserMiddleware',
]

# Sends queries for company data (members, expenses, materials...) to
# that company's own dedicated database, and keeps platform data
# (accounts, company registrations, audit log) on 'default'. Without
# this, every company's dedicated database would sit empty and unused.
DATABASE_ROUTERS = ['core.db_router.TenantRouter']

ROOT_URLCONF = 'construction_mgmt.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.active_project',
            ],
        },
    },
]

WSGI_APPLICATION = 'construction_mgmt.wsgi.application'


# ============================================================
# DATABASE
# ============================================================
#
# By default this uses MySQL, as requested. Set the DJANGO_DB_ENGINE
# environment variable to 'sqlite' to run locally without MySQL installed
# (handy for a quick first test-drive before you set up MySQL).
# ============================================================

if DJANGO_DB_ENGINE == 'sqlite':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
else:
     DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'friendstechbd_housing',
            'USER': 'friendstechbd_Alex2',
            'PASSWORD': '^RI@58V?@3ps',
            'HOST': 'localhost',
            'PORT': '3306',
            'OPTIONS': {
                'charset': 'utf8mb4',
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            },
        }
    }

# ============================================================
# CUSTOM USER MODEL
# ============================================================

AUTH_USER_MODEL = 'accounts.CustomUser'


# ============================================================
# PASSWORD VALIDATION
# ============================================================

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 / TIME ZONE
# ============================================================

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_TZ = True


# ============================================================
# STATIC / MEDIA FILES
# ============================================================

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'


# ============================================================
# LOGIN / LOGOUT
# ============================================================

LOGIN_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/dashboard/'
LOGOUT_REDIRECT_URL = '/accounts/login/'


# ============================================================
# CSRF
# ============================================================

CSRF_TRUSTED_ORIGINS = [h.strip() for h in os.environ.get(
    'DJANGO_CSRF_TRUSTED_ORIGINS',
    'http://127.0.0.1:8000,http://localhost:8000',
).split(',') if h.strip()]

# Production-safe browser/session hardening. Set DJANGO_SECURE_COOKIES=True
# behind HTTPS (recommended for production).
SECURE_COOKIES = os.environ.get('DJANGO_SECURE_COOKIES', 'False').strip().lower() in {'1', 'true', 'yes'}
SESSION_COOKIE_SECURE = SECURE_COOKIES
CSRF_COOKIE_SECURE = SECURE_COOKIES
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SAMESITE = 'Lax'
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_REFERRER_POLICY = 'same-origin'
X_FRAME_OPTIONS = 'DENY'
if SECURE_COOKIES:
    SECURE_SSL_REDIRECT = True
    SECURE_HSTS_SECONDS = 31536000
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = False


# ============================================================
# SESSION
# ============================================================

SESSION_COOKIE_AGE = 60 * 60 * 8
SESSION_EXPIRE_AT_BROWSER_CLOSE = False


# ============================================================
# FILE UPLOAD
# ============================================================

FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024
DATA_UPLOAD_MAX_MEMORY_SIZE = 20 * 1024 * 1024


# ============================================================
# DEFAULT PRIMARY KEY
# ============================================================

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
