"""Django settings for the billing reconciliation service."""

from pathlib import Path

from celery.schedules import crontab

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

SECRET_KEY = "dev-only-not-a-real-secret"
DEBUG = True
ALLOWED_HOSTS = ["*"]

INSTALLED_APPS = [
    "django.contrib.contenttypes",
    "django.contrib.auth",
    "adjustments",
    "api",
]

MIDDLEWARE: list[str] = []
ROOT_URLCONF = "billing.urls"
USE_TZ = True
TIME_ZONE = "UTC"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "billing",
        "USER": "root",
        "PASSWORD": "billing",
        "HOST": "mysql",
        "PORT": "3306",
        "OPTIONS": {
            "charset": "utf8mb4",
        },
        "TEST": {"CHARSET": "utf8mb4"},
    }
}

REDIS_URL = "redis://redis:6379/0"

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": REDIS_URL,
    }
}

# --- Celery -----------------------------------------------------------------
CELERY_BROKER_URL = REDIS_URL
CELERY_RESULT_BACKEND = REDIS_URL
CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TIMEZONE = "UTC"

# Redelivery safety net: if a worker dies mid-task the broker hands the message
# to another worker rather than dropping it.
CELERY_TASK_ACKS_LATE = True
CELERY_WORKER_PREFETCH_MULTIPLIER = 1

# How long the broker waits before deciding a task was abandoned.
CELERY_BROKER_TRANSPORT_OPTIONS = {"visibility_timeout": 30}

# Remediation item 2 from incident 2026-03-14: keep cache memory bounded.
CELERY_BEAT_SCHEDULE = {
    "nightly-cache-purge": {
        "task": "adjustments.maintenance.purge_cache",
        "schedule": crontab(hour=4, minute=0),
    }
}
