"""Django settings for aiservice project.

Generated by 'django-admin startproject' using Django 5.0.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from __future__ import annotations

import os
from pathlib import Path

import dj_database_url
import dotenv
import sentry_sdk

dotenv.load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR: Path = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
if os.environ.get("ENVIRONMENT") == "PRODUCTION":
    SECRET_KEY: str | None = os.environ.get("SECRET_KEY")
    os.environ["DATABASE_URL"] = os.environ.get("POSTGRESQLCONNSTR_DATABASE_URL")  # type: ignore[assignment]
    DEBUG: bool = False
else:
    env_vars: dict[str, str | None] = dotenv.dotenv_values()
    SECRET_KEY = env_vars.get("SECRET_KEY", os.environ.get("SECRET_KEY"))
    DEBUG = True

assert "DATABASE_URL" in os.environ, "DATABASE_URL environment variable not set"
ALLOWED_HOSTS: list[str] = [
    "localhost",
    "codeflash.ai",
    "app.codeflash.ai",
    "codeflash-aiservice.azurewebsites.net",
    "codeflash-aiservice-dev.azurewebsites.net",
] + [h for h in os.environ.get("EXTRA_ALLOWED_HOSTS", "").split(",") if h]


# Application definition

INSTALLED_APPS: list[str] = [
    "core.apps.CoreConfig",
    "authapp.apps.AuthAppConfig",
    "django.contrib.contenttypes",
    "django.contrib.staticfiles",
    "core.log_features.apps.LoggingConfig",
    "aiservice.apps.AiServiceConfig",  # Add the app containing the management commands
]

MIDDLEWARE: list[str] = [
    "django.middleware.security.SecurityMiddleware",
    "django.middleware.common.CommonMiddleware",
    "aiservice.middleware.healthcheck.HealthCheckMiddleware",
    "aiservice.middleware.auth_middleware.AuthMiddleware",
    "aiservice.middleware.rate_limit.RateLimitMiddleware",
    "aiservice.middleware.track_usage_middleware.TrackUsageMiddleware",
]

ROOT_URLCONF: str = "aiservice.urls"

TEMPLATES: list[str] = []

WSGI_APPLICATION: str = "aiservice.wsgi.application"


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
# Requires DATABASE_URL environment variable to be set

assert "DATABASE_URL" in os.environ, "DATABASE_URL environment variable not set"
DATABASES = {"default": dj_database_url.config(conn_max_age=0)}
# psycopg3 native connection pooling — replaces persistent connections (conn_max_age)
# which don't work correctly under ASGI. The pool is managed by psycopg_pool.ConnectionPool.
DATABASES["default"]["OPTIONS"] = {"pool": {"min_size": 2, "max_size": 100}}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS: list[dict[str, str]] = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE: str = "en-us"

TIME_ZONE: str = "UTC"

USE_I18N: bool = True

USE_TZ: bool = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL: str = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD: str = "django.db.models.BigAutoField"

# Logging — explicit config prevents unbounded record buffering.
# Django's default adds AdminEmailHandler which buffers; Sentry's LoggingIntegration
# adds handlers that capture every record.  StreamHandler writes + flushes immediately.
# django.request at ERROR skips 4xx WARNING logs whose args pin the full ASGIRequest
# (headers, body, payload) in memory for the lifetime of the LogRecord.
LOGGING: dict[str, object] = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "root": {"handlers": ["console"], "level": "WARNING"},
    "loggers": {
        "django": {"handlers": ["console"], "level": "INFO", "propagate": False},
        "django.request": {"level": "ERROR"},
    },
}

# Sentry
if os.environ.get("ENVIRONMENT", default="") == "PRODUCTION":
    sentry_sdk.init(
        dsn="https://8a857cbf974ca889a46c1b39173db44b@o4506833230561280.ingest.sentry.io/4506833234493440",
        traces_sample_rate=0.1,
        profiles_sample_rate=0.01,
    )
