"""Base Django settings for an Andrea web service — the framework-only common denominator
factored out of uuid_service (the proven Django/DRF template). A service does:

    from andrea_svc_web.settings import *          # noqa: F401,F403

then sets only what is service-specific: SERVICE_NAME, ROOT_URLCONF, WSGI_APPLICATION, its app
in INSTALLED_APPS, its SPECTACULAR_SETTINGS title/description, and (optionally) SVC_HEALTHCHECK.

Design invariants (operator directives):
  * No ORM apps (no contenttypes/auth): modern Django runs as a pure framework. DATABASES is
    intentionally empty — a service owns its own storage (raw SQL / an external store).
  * OpenAPI for free via drf-spectacular at /api/schema + /api/docs (the "all API methods in
    wiki + OpenAPI" directive).
  * Auth is config-driven via andrea_svc_auth: set ANDREA_SVC_KEYS (done here from the standard
    ANDREA_SVC_API_KEY env) to turn on API-key auth; OIDC turns on when OIDC_ISSUER/JWKS are set.
"""
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


def _bool(key: str, default: str = "0") -> bool:
    return os.environ.get(key, default).lower() in ("1", "true", "yes", "on")


# ── ConfigServer overlay (operator 2026-07-19: "ConfigServer for secrets and tweaks") ─────────────
# BEFORE reading any env-based setting below, overlay this service's central config — secrets + live
# tweaks — from the config-service onto os.environ, so everything downstream (SECRET_KEY, DB_*, auth
# keys, service knobs) transparently picks it up and dot-envs can retire. Opt-in + FAIL-SOFT: enabled
# by ANDREA_CONFIG_SERVICE=1 with SERVICE_NAME (+ optional BOX) set; a config-service outage leaves
# env untouched (degrades to the baked-in defaults, never an outage).
if _bool("ANDREA_CONFIG_SERVICE"):
    from andrea_svc_web.config import apply_to_env as _apply_config
    _apply_config(os.environ.get("SERVICE_NAME", ""), os.environ.get("BOX"))


# Internal service (service_pool); the nginx/network ACL is the gate. A dev-only secret by default.
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "dev-only-not-for-prod-change-me")
DEBUG = _bool("DJANGO_DEBUG")
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "*").split(",")

# staticfiles is only for the Swagger UI; rest_framework + drf_spectacular are the API stack.
# andrea_svc_web is listed so its AppConfig.ready() registers the shared OpenAPI auth-scheme
# extension. A service APPENDS its own app: INSTALLED_APPS = INSTALLED_APPS + ["myservice.app"].
INSTALLED_APPS = [
    "django.contrib.staticfiles",
    "rest_framework",
    "drf_spectacular",
    "andrea_svc_web",
]

MIDDLEWARE = [
    "django.middleware.common.CommonMiddleware",
]

TEMPLATES = [{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "APP_DIRS": True,
    "DIRS": [],
    "OPTIONS": {},
}]

# Django manages NO database — a service owns its storage directly (operator: "you can have a
# Django service without a DB at all"). A service that DOES want the ORM can override this.
DATABASES = {}

REST_FRAMEWORK = {
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
    "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
    "UNAUTHENTICATED_USER": None,
    # Transparent pass-through to DRF's default UNLESS ANDREA_FASTAPI_COMPAT_422 is on (below).
    "EXCEPTION_HANDLER": "andrea_svc_web.exceptions.fastapi_compat_exception_handler",
}

# Optional FastAPI-compat: render validation errors as HTTP 422 {"detail":[{loc,msg,type}]} instead
# of DRF's standard 400 — for a service migrating from FastAPI that must preserve that wire shape.
# OFF by default (standard 400). A useful option to have, not a default.
ANDREA_FASTAPI_COMPAT_422 = _bool("ANDREA_FASTAPI_COMPAT_422")

# A service overrides TITLE/DESCRIPTION/VERSION: SPECTACULAR_SETTINGS = {**SPECTACULAR_SETTINGS, ...}
SPECTACULAR_SETTINGS = {
    "TITLE": "Andrea Service",
    "DESCRIPTION": "An Andrea web service (andrea_svc_web base).",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
}

# ── service auth (andrea_svc_auth) ──────────────────────────────────────────────────────────────
# API-key path: set ANDREA_SVC_KEYS (a single secret str or a {key_id: secret} map). We default it
# from the standard ANDREA_SVC_API_KEY env so a service inherits API-key auth with zero config.
# Unset (dev) => ServiceKeyRequiredIfConfigured is a no-op (open), matching the hand-rolled services.
ANDREA_SVC_KEYS = os.environ.get("ANDREA_SVC_API_KEY") or None
ANDREA_API_KEY_HEADER = os.environ.get("ANDREA_API_KEY_HEADER", "X-Agent-Key")
# OIDC path (off unless both are set): OIDC_ISSUER, OIDC_JWKS_URL, OIDC_AUDIENCE.
OIDC_ISSUER = os.environ.get("OIDC_ISSUER", "")
OIDC_JWKS_URL = os.environ.get("OIDC_JWKS_URL", "")

# ── service identity + health ───────────────────────────────────────────────────────────────────
SERVICE_NAME = os.environ.get("SERVICE_NAME", "andrea-service")
# Optional deep health-check: a "module.path:callable" returning truthy when healthy (e.g. a real
# DB SELECT 1). None => /health is pure liveness.
SVC_HEALTHCHECK = None

# ── Syslog logging (operator 2026-07-19: "Syslog logging") ────────────────────────────────────────
# Ship logs to stdout (docker/journald still capture them) AND syslog, tagged with SERVICE_NAME.
# Env-tunable: SYSLOG_ADDRESS (default /dev/log), SYSLOG_FACILITY (local0), LOG_LEVEL, ANDREA_SYSLOG=0
# to disable. Fail-soft: syslog is skipped if its target isn't present (no /dev/log socket) → stdout only.
# A service that OVERRIDES SERVICE_NAME after `from andrea_svc_web.settings import *` should re-run
# `LOGGING = build_logging(SERVICE_NAME)` (or set SERVICE_NAME via env) so the syslog tag matches.
from andrea_svc_web.logging_conf import build_logging as _build_logging  # noqa: E402
LOGGING = _build_logging(SERVICE_NAME)
# Rebuild LOGGING from the FINAL SERVICE_NAME at startup (after the whole settings module loads), so a
# service that overrides SERVICE_NAME after the star-import is still syslog-tagged correctly WITHOUT a
# per-service `LOGGING = build_logging(SERVICE_NAME)` re-run. Fixes the fleet-wide mis-tag-as-"andrea-service".
LOGGING_CONFIG = "andrea_svc_web.logging_conf.configure"

STATIC_URL = "static/"
USE_TZ = True
