import os
from pathlib import Path
from dotenv import load_dotenv

# BASE_DIR = core directory
BASE_DIR = Path(__file__).resolve().parent

# Set up module sys.path so that all apps are cleanly discoverable
from core.loader import setup_module_paths, get_installed_apps
setup_module_paths(BASE_DIR)

# Load environment variables from .env inside core if present, or parent .env
if (BASE_DIR / '.env').exists():
    load_dotenv(BASE_DIR / '.env')
else:
    load_dotenv(BASE_DIR.parent / '.env')

SECRET_KEY = os.environ.get('SECRET_KEY', 'insecure-default-key-change-in-production')
DEBUG = os.environ.get('DEBUG', 'True').lower() in ('true', '1', 'yes')

ALLOWED_HOSTS = [host.strip() for host in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1,10.0.2.2,testserver').split(',') if host.strip()]
if 'testserver' not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append('testserver')
if DEBUG and '*' not in ALLOWED_HOSTS:
    ALLOWED_HOSTS.append('*')

# Application definition: Core + Django + RestFramework + Feature Apps
INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'rest_framework',
    'drf_spectacular',
    'core.apps.CoreConfig',
] + get_installed_apps(BASE_DIR)

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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 = 'core.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

# Database
# Uses SQLite on development (default) or MySQL on production when DB_ENGINE=mysql
# or when MySQL environment variables (DB_NAME, DB_USER) are configured.
db_engine = os.environ.get('DB_ENGINE', '').lower()
db_name = os.environ.get('DB_NAME', '')

if db_engine == 'mysql' or (db_engine != 'sqlite' and not DEBUG and db_name):
    # Enable PyMySQL fallback if mysqlclient C extension is not installed
    try:
        import pymysql
        pymysql.install_as_MySQLdb()
    except ImportError:
        pass

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': db_name,
            'USER': os.environ.get('DB_USER', ''),
            'PASSWORD': os.environ.get('DB_PASSWORD', ''),
            'HOST': os.environ.get('DB_HOST', 'localhost'),
            'PORT': os.environ.get('DB_PORT', '3306'),
            'OPTIONS': {
                'charset': 'utf8mb4',
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            },
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }

AUTH_USER_MODEL = 'accounts.User'

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 10,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files served by WhiteNoise (Django admin, DRF browsable API)
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = []
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Session & Security Settings
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = 'Lax'

# Session Expiration:
# Default session age for web: 7 days of inactivity (sliding window)
# Mobile clients use remember_me=True for persistent long-lived sessions
SESSION_COOKIE_AGE = 7 * 24 * 60 * 60  # 7 days (604800 seconds)
SESSION_SAVE_EVERY_REQUEST = True      # Refresh 7-day expiration on every user activity

SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'
SECURE_REFERRER_POLICY = 'same-origin'

if not DEBUG:
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True

_csrf_origins = [
    origin.strip()
    for origin in os.environ.get(
        'CSRF_TRUSTED_ORIGINS',
        'http://localhost:8000,http://127.0.0.1:8000,http://10.0.2.2:8000,http://localhost:5173,http://127.0.0.1:5173,https://chithie.com,https://www.chithie.com,https://api.chithie.com'
    ).split(',')
    if origin.strip()
]
CSRF_TRUSTED_ORIGINS = _csrf_origins

# REST Framework settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'authentication.CsrfExemptSessionAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
    'EXCEPTION_HANDLER': 'core.exceptions.custom_exception_handler',
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
}

SPECTACULAR_SETTINGS = {
    'TITLE': 'Chithie Core API',
    'DESCRIPTION': 'REST API documentation for messaging, user management, moderation, and notifications.',
    'VERSION': '1.0.0',
    'SERVE_INCLUDE_SCHEMA': False,
    'COMPONENT_SPLIT_REQUEST': True,
}

# Site & Email Settings
SITE_URL = os.environ.get('SITE_URL', 'http://localhost:8000')
ADMIN_URL_PATH = os.environ.get('ADMIN_URL_PATH', 'admin/')
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'chithie <noreply@example.com>')

# Email Settings
import django

_email_backend = os.environ.get('EMAIL_BACKEND', 'django.core.mail.backends.locmem.EmailBackend')
_email_host = os.environ.get('EMAIL_HOST', 'localhost')
_email_port = int(os.environ.get('EMAIL_PORT', '587'))
_email_user = os.environ.get('EMAIL_HOST_USER', '')
_email_password = os.environ.get('EMAIL_HOST_PASSWORD', '')
_email_use_tls = os.environ.get('EMAIL_USE_TLS', 'True').lower() in ('true', '1', 'yes')
_email_use_ssl = os.environ.get('EMAIL_USE_SSL', 'False').lower() in ('true', '1', 'yes')

if django.VERSION[0] >= 6:
    MAILERS = {
        'default': {
            'BACKEND': _email_backend,
            'OPTIONS': {
                'host': _email_host,
                'port': _email_port,
                'username': _email_user,
                'password': _email_password,
                'use_tls': _email_use_tls,
                'use_ssl': _email_use_ssl,
            }
        }
    }
else:
    EMAIL_BACKEND = _email_backend
    EMAIL_HOST = _email_host
    EMAIL_PORT = _email_port
    EMAIL_HOST_USER = _email_user
    EMAIL_HOST_PASSWORD = _email_password
    EMAIL_USE_TLS = _email_use_tls
    EMAIL_USE_SSL = _email_use_ssl

# CAPTCHA configuration
import sys
_is_testing = 'pytest' in sys.modules or 'test' in sys.argv
CAPTCHA_ENABLED = os.environ.get('CAPTCHA_ENABLED', 'False' if _is_testing else 'True').lower() not in ('false', '0', 'no')
CAPTCHA_VERIFY_URL = os.environ.get('CAPTCHA_VERIFY_URL', 'https://hcaptcha.com/siteverify')
CAPTCHA_SECRET_KEY = os.environ.get('CAPTCHA_SECRET_KEY', '')
CAPTCHA_SITE_KEY = os.environ.get('CAPTCHA_SITE_KEY', '')

# CORS Configuration (allows web SPA on port 5173 / localhost to call API)
CORS_ALLOW_ALL_ORIGINS = DEBUG
CORS_ALLOWED_ORIGINS = [
    'http://localhost:5173',
    'http://127.0.0.1:5173',
    'http://localhost:3000',
    'http://127.0.0.1:3000',
    'https://chithie.com',
    'https://www.chithie.com',
]
CORS_ALLOW_CREDENTIALS = True
