"""
Local development settings for thrillwiki project.

This module extends base.py with development-specific configurations:
- Debug mode enabled
- Local memory cache (no Redis required)
- Console email backend option
- Development middleware (nplusone, debug toolbar)
- Enhanced logging for debugging
"""

import logging

from .base import *  # noqa: F401,F403

# =============================================================================
# Development Settings
# =============================================================================

DEBUG = True

# For local development, allow all hosts
ALLOWED_HOSTS = ["*"]

# CSRF trusted origins for local development
CSRF_TRUSTED_ORIGINS = [
    "http://localhost:8000",
    "http://127.0.0.1:8000",
    "https://beta.thrillwiki.com",
]

# =============================================================================
# GeoDjango Library Paths (macOS with Homebrew)
# =============================================================================

GDAL_LIBRARY_PATH = "/opt/homebrew/lib/libgdal.dylib"
GEOS_LIBRARY_PATH = "/opt/homebrew/lib/libgeos_c.dylib"

# =============================================================================
# Local Cache Configuration
# =============================================================================
# Use local memory cache for development (no Redis required)

LOC_MEM_CACHE_BACKEND = "django.core.cache.backends.locmem.LocMemCache"

CACHES = {
    "default": {
        "BACKEND": LOC_MEM_CACHE_BACKEND,
        "LOCATION": "unique-snowflake",
        "TIMEOUT": 300,  # 5 minutes
        "OPTIONS": {"MAX_ENTRIES": 1000},
    },
    "sessions": {
        "BACKEND": LOC_MEM_CACHE_BACKEND,
        "LOCATION": "sessions-cache",
        "TIMEOUT": 86400,  # 24 hours
        "OPTIONS": {"MAX_ENTRIES": 5000},
    },
    "api": {
        "BACKEND": LOC_MEM_CACHE_BACKEND,
        "LOCATION": "api-cache",
        "TIMEOUT": 300,  # 5 minutes
        "OPTIONS": {"MAX_ENTRIES": 2000},
    },
}

# Development-friendly cache settings
CACHE_MIDDLEWARE_SECONDS = 1  # Very short cache for development
CACHE_MIDDLEWARE_KEY_PREFIX = "thrillwiki_dev"

# =============================================================================
# Email Backend
# =============================================================================
# Use ForwardEmail for actual sending, or console for debugging

# Console backend for debugging (uncomment to use):
# EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

# ForwardEmail backend for actual email sending:
EMAIL_BACKEND = "django_forwardemail.backends.ForwardEmailBackend"

# =============================================================================
# Security Settings (Relaxed for Development)
# =============================================================================

SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False

# =============================================================================
# Development Apps
# =============================================================================

DEVELOPMENT_APPS = [
    # "silk",  # Disabled for performance
    "nplusone.ext.django",
    "django_extensions",
    "widget_tweaks",
]

# Add development apps if not already present
for app in DEVELOPMENT_APPS:
    if app not in INSTALLED_APPS:  # noqa: F405
        INSTALLED_APPS.append(app)  # noqa: F405

# =============================================================================
# Development Middleware
# =============================================================================

DEVELOPMENT_MIDDLEWARE = [
    # "silk.middleware.SilkyMiddleware",  # Disabled for performance
    "nplusone.ext.django.NPlusOneMiddleware",
    # Note: PerformanceMiddleware and QueryCountMiddleware are already in base.py MIDDLEWARE
    "apps.core.middleware.nextjs.APIResponseMiddleware",
    "apps.core.middleware.request_logging.RequestLoggingMiddleware",
]

# Add development middleware if not already present
for middleware in DEVELOPMENT_MIDDLEWARE:
    if middleware not in MIDDLEWARE:  # noqa: F405
        MIDDLEWARE.insert(1, middleware)  # noqa: F405

# =============================================================================
# Debug Toolbar Configuration
# =============================================================================

INTERNAL_IPS = ["127.0.0.1", "::1"]

# =============================================================================
# NPlusOne Configuration
# =============================================================================
# Detects N+1 query issues during development

NPLUSONE_LOGGER = logging.getLogger("nplusone")
NPLUSONE_LOG_LEVEL = logging.WARN

# =============================================================================
# Development Logging Configuration
# =============================================================================
# Extended logging for debugging with reduced noise

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}",
            "style": "{",
        },
        "json": {
            "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
            "format": ("%(levelname)s %(asctime)s %(module)s %(process)d " "%(thread)d %(message)s"),
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
        "file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": BASE_DIR / "logs" / "thrillwiki.log",  # noqa: F405
            "maxBytes": 1024 * 1024 * 10,  # 10MB
            "backupCount": 5,
            "formatter": "json",
        },
        "performance": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": BASE_DIR / "logs" / "performance.log",  # noqa: F405
            "maxBytes": 1024 * 1024 * 10,  # 10MB
            "backupCount": 5,
            "formatter": "json",
        },
    },
    "root": {
        "level": "INFO",
        "handlers": ["console"],
    },
    "loggers": {
        "django": {
            "handlers": ["file"],
            "level": "WARNING",
            "propagate": False,
        },
        "django.db.backends": {
            "handlers": ["console"],
            "level": "WARNING",
            "propagate": False,
        },
        "thrillwiki": {
            "handlers": ["console", "file"],
            "level": "INFO",
            "propagate": False,
        },
        "performance": {
            "handlers": ["performance"],
            "level": "WARNING",
            "propagate": False,
        },
        "query_optimization": {
            "handlers": ["console", "file"],
            "level": "WARNING",
            "propagate": False,
        },
        "nplusone": {
            "handlers": ["console"],
            "level": "ERROR",
            "propagate": False,
        },
        "request_logging": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
    },
}
