from pathlib import Path
import os
from importlib.util import find_spec

from dotenv import load_dotenv

# Sentry is optional — guard import so a missing package never prevents startup
try:
    import sentry_sdk
    from sentry_sdk.integrations.django import DjangoIntegration
    from sentry_sdk.integrations.celery import CeleryIntegration
    _sentry_available = True
except ImportError:
    _sentry_available = False

# BASE_DIR -> backend/ (project root for Django app)
BASE_DIR = Path(__file__).resolve().parent.parent.parent


def _csv_env(var_name, default=''):
    raw = os.getenv(var_name, default)
    return [item.strip() for item in raw.split(',') if item and item.strip()]

# load .env from project root if present
load_dotenv(os.path.join(BASE_DIR, '.env'))

# SECURITY
SECRET_KEY = os.getenv('SECRET_KEY', 'django-insecure-dev-key')

# Application definition
BASE_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

if find_spec('daphne'):
    BASE_APPS.insert(0, 'daphne')

THIRD_PARTY_APPS = [
    app_name
    for module_name, app_name in [
        ('rest_framework', 'rest_framework'),
        ('corsheaders', 'corsheaders'),
        ('channels', 'channels'),
        ('django_celery_results', 'django_celery_results'),
        ('drf_spectacular', 'drf_spectacular'),
    ]
    if find_spec(module_name)
]


# Local apps: core is always enabled; add all business and project apps explicitly
LOCAL_APPS = [
    'apps.platform.core',
    'apps.platform.settings',
    'apps.accounts',
    'apps.audit',
    'apps.business.schemes',
    'apps.business.products',
    'apps.business.orders',
    'apps.business.invoice',
    'apps.business.distributor',
    # 'apps.business.geo',
    'apps.business.lucky_dip',
    # 'apps.business.masterdata',
    # 'apps.business.payments',
    'apps.business.pool',
    'apps.business.power_stream',
    'apps.business.rewards',
    'apps.business.binary_tree',
    'apps.business.network_chat',
    'apps.business.wallet',
    'apps.business.withdrawals',
    'apps.business.marketplace',
    # 'apps.core',
    'apps.featureflags',
    # 'apps.geo',
    # 'apps.masterdata',
    'apps.notifications',
    'apps.support',
    'apps.company',
    'apps.telemetry',
    'apps.leads',
    # 'apps.payments',
    'apps.platform',
]

try:
    from ..modules import ENABLED_MODULES
except Exception:
    ENABLED_MODULES = []

for module in ENABLED_MODULES:
    if f'apps.{module}' not in LOCAL_APPS:
        LOCAL_APPS.append(f'apps.{module}')

INSTALLED_APPS = BASE_APPS + THIRD_PARTY_APPS + LOCAL_APPS

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
]

try:
    if 'audit' in ENABLED_MODULES:
        auth_index = MIDDLEWARE.index('django.contrib.auth.middleware.AuthenticationMiddleware')
        MIDDLEWARE.insert(auth_index + 1, 'apps.audit.middleware.AuditMiddleware')
except Exception:
    pass

try:
    if 'tenancy' in ENABLED_MODULES:
        sess_index = MIDDLEWARE.index('django.contrib.sessions.middleware.SessionMiddleware')
        MIDDLEWARE.insert(sess_index + 1, 'apps.platform.tenancy.middleware.TenantMiddleware')
except Exception:
    pass

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'

# Internationalization
LANGUAGE_CODE = 'en'
LANGUAGES = [
    ('en', 'English'),
    ('hi', 'Hindi'),
    ('te', 'Telugu'),
]
LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]
TIME_ZONE = os.getenv('TIME_ZONE', 'Asia/Kolkata')
USE_I18N = True
USE_TZ = True

# Static & Media
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# REST framework
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/hour',
        'user': '1000/hour',
        # custom scopes
        'login': '5/minute',
        'otp': '3/minute',
        'lead_submit': '30/minute',
        'purchase': '10/minute',  # adjust as needed
        'withdrawal': '3/hour',   # adjust as needed
    },
}


# CORS
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = _csv_env(
    'CORS_ALLOWED_ORIGINS',
    'http://localhost:5173,http://localhost:3000,https://truewaveindia.com,https://www.truewaveindia.com'
)
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = _csv_env(
    'CSRF_TRUSTED_ORIGINS',
    'http://localhost:5173,http://localhost:3000,https://api.truewaveindia.com,https://truewaveindia.com,https://www.truewaveindia.com'
)

# Custom user model
AUTH_USER_MODEL = os.getenv('AUTH_USER_MODEL', 'accounts.User')

# OTP expiries
EMAIL_OTP_EXPIRY_MINUTES = int(os.getenv('EMAIL_OTP_EXPIRY_MINUTES', '5'))
MOBILE_OTP_EXPIRY_MINUTES = int(os.getenv('MOBILE_OTP_EXPIRY_MINUTES', '10'))

# Google OAuth
GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID', '')
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET', '')

# Email SMTP
EMAIL_HOST = os.getenv('EMAIL_HOST', 'smtp.gmail.com')
EMAIL_PORT = int(os.getenv('EMAIL_PORT', '587'))
EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS', 'True').lower() in ('1', 'true', 'yes')
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD', '')
DEFAULT_FROM_EMAIL = os.getenv('DEFAULT_FROM_EMAIL', EMAIL_HOST_USER or 'noreply@truwaveindia.com')
EMAIL_FROM_NAME = os.getenv('EMAIL_FROM_NAME', 'True Wave Marketing')

# JWT
from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=int(os.getenv('ACCESS_TOKEN_LIFETIME', '60'))),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=int(os.getenv('REFRESH_TOKEN_LIFETIME', '1'))),
    'SIGNING_KEY': os.getenv('JWT_SECRET_KEY', SECRET_KEY),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': False,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
}

# Celery
REDIS_URL = os.getenv('REDIS_URL', 'redis://localhost:6379/0')
CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL', REDIS_URL)
CELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND', 'django-db')
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = TIME_ZONE

# OpenAPI
SPECTACULAR_SETTINGS = {
    'TITLE': 'Backend Platform API',
    'DESCRIPTION': 'API documentation for the backend platform template.',
    'VERSION': os.getenv('TEMPLATE_VERSION', '1.0.0'),
}

# Enhanced logging: console + file
import os
LOG_DIR = os.path.join(BASE_DIR, 'logs')
os.makedirs(LOG_DIR, exist_ok=True)
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[{asctime}] {levelname} {name} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'backend.log'),
            'formatter': 'verbose',
            'level': 'DEBUG',
        },
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': os.getenv('LOG_LEVEL', 'DEBUG'),
    },
}

# Sentry configuration: initialize only when SENTRY_DSN is provided
SENTRY_DSN = os.getenv('SENTRY_DSN', '')
if SENTRY_DSN and _sentry_available:
    try:
        sentry_sdk.init(
            dsn=SENTRY_DSN,
            integrations=[DjangoIntegration(), CeleryIntegration()],
            traces_sample_rate=float(os.getenv('SENTRY_TRACES_SAMPLE_RATE', '0.1')),
            send_default_pii=os.getenv('SENTRY_SEND_DEFAULT_PII', 'true').lower() in ('1', 'true', 'yes'),
        )
    except Exception:
        # Do not fail startup if Sentry initialization fails
        pass

# Channels Configuration (WebSocket)
ASGI_APPLICATION = 'config.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [os.getenv('REDIS_URL', 'redis://localhost:6379/1')],
        },
    },
}
# Fallback to in-memory channel layer for development (no Redis)
if os.getenv('USE_IN_MEMORY_CHANNELS', 'false').lower() in ('1', 'true', 'yes'):
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels.layers.InMemoryChannelLayer'
        }
    }
