"""Local development settings.

Selected with DJANGO_SETTINGS_MODULE=config.settings.dev. Everything not named
here comes from base.py and stays env-driven, so .env keeps working unchanged.

The point of this module is to make development fail *loudly and locally*
instead of quietly behaving like a misconfigured production host.
"""

from .base import *  # noqa: F401,F403
from .base import _env_bool, _redis_url, os

# Debug is the default here rather than something you must remember to set.
DEBUG = _env_bool('DJANGO_DEBUG', True)

# Any host: dev is reached as localhost, 127.0.0.1 and a LAN IP (phone testing).
ALLOWED_HOSTS = ['*']

# Cache: prefer a real Redis when one is actually reachable, otherwise LocMem.
#
# base.py selects ResilientRedisCache whenever REDIS_URL is set, which by design
# swallows connection errors. In production that is correct — a dead Redis must
# not take down login. In development it is actively harmful: with no Redis
# running, every cache.get() silently returns None, so caching bugs and
# throttling logic appear to work and only break once deployed. Probing here
# means dev either gets a working cache or an honest in-process one.
def _redis_reachable(url, timeout=0.2):
    """True if a TCP/unix Redis at `url` accepts a connection right now."""
    import socket
    from urllib.parse import urlparse

    if not url:
        return False
    if url.startswith('unix://'):
        path = urlparse(url).path
        family, address = socket.AF_UNIX, path
    else:
        parsed = urlparse(url)
        family = socket.AF_INET
        address = (parsed.hostname or '127.0.0.1', parsed.port or 6379)
    try:
        with socket.socket(family, socket.SOCK_STREAM) as sock:
            sock.settimeout(timeout)
            sock.connect(address)
        return True
    except OSError:
        return False


if not _redis_reachable(_redis_url):
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'khub-locmem',
        }
    }
    # In-memory channel layer: WebSocket fan-out works within a single process,
    # which is all runserver provides anyway.
    CHANNEL_LAYERS = {
        'default': {'BACKEND': 'channels.layers.InMemoryChannelLayer'},
    }

# Never send real mail from a developer machine, whatever .env says.
EMAIL_BACKEND = os.environ.get(
    'DJANGO_EMAIL_BACKEND', 'django.core.mail.backends.console.EmailBackend'
)

# Media stays on local disk in dev even if R2 credentials are present in .env:
# a developer's uploads must not land in a production bucket.
STORAGES = {
    **STORAGES,  # noqa: F405
    'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
}

# HTTPS-only machinery off: runserver is plain HTTP, so secure cookies would
# never be sent and HSTS would poison the browser for localhost.
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SAMESITE = 'Lax'
SECURE_PROXY_SSL_HEADER = None
SECURE_HSTS_SECONDS = 0
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False

# No proxy in front of runserver, so X-Forwarded-For must not be trusted —
# otherwise a client can spoof its own IP past throttling and django-axes.
BEHIND_CLOUDFLARE = False
TRUSTED_PROXY_COUNT = 0

# Run background/Celery work inline so a developer sees the traceback instead of
# a task vanishing into a worker that is not running.
BACKGROUND_TASKS_EAGER = _env_bool('BACKGROUND_TASKS_EAGER', True)
CELERY_TASK_ALWAYS_EAGER = _env_bool('CELERY_TASK_ALWAYS_EAGER', True)
CELERY_TASK_EAGER_PROPAGATES = True
