import os
import sys
from pathlib import Path

import dj_database_url
from celery.schedules import crontab
from dotenv import load_dotenv

TRUTHY = ("true", "1", "t")

PROJECT_ROOT = Path(__file__).resolve().parent
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps"))

# Tap vrobbler.conf if it's available
if os.path.exists("vrobbler.conf"):
    load_dotenv("vrobbler.conf")
elif os.path.exists("/etc/vrobbler.conf"):
    load_dotenv("/etc/vrobbler.conf")
elif os.path.exists("/usr/local/etc/vrobbler.conf"):
    load_dotenv("/usr/local/etc/vrobbler.conf")

# Build paths inside the project like this: BASE_DIR / 'subdir'.


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("VROBBLER_SECRET_KEY", "not-a-secret-234lkjasdflj132")


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("VROBBLER_DEBUG", "false").lower() in TRUTHY

TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"

TAGGIT_CASE_INSENSITIVE = True

KEEP_DETAILED_SCROBBLE_LOGS = os.getenv("VROBBLER_KEEP_DETAILED_SCROBBLE_LOGS", False)

# Log keys to strip from a scrobble's log when rendering a public/shared link.
# Keyed by scrobble media_type label. These are fields that may expose
# sensitive personal information (e.g. body composition) to anyone with the link.
SENSITIVE_LOGDATA_KEYS = {
    "Task": [
        "body_fat",
        "bmi",
        "muscle",
        "bone",
        "water",
        "visceral_fat",
        "waist",
        "lbm",
    ],
    "Workout": ["bodyweight_kg"],
}

# Key must be 16, 24 or 32 bytes long and will be converted to a byte stream
ENCRYPTED_FIELD_KEY = os.getenv(
    "VROBBLER_ENCRYPTED_FIELD_KEY", "12345678901234567890123456789012"
)

DJANGO_ENCRYPTED_FIELD_KEY = bytes(ENCRYPTED_FIELD_KEY, "utf-8")

# Should we cull old in-progress scrobbles that are beyond the wait period for resuming?
DELETE_STALE_SCROBBLES = (
    os.getenv("VROBBLER_DELETE_STALE_SCROBBLES", "true").lower() in TRUTHY
)

# Used to dump data coming from srobbling sources, helpful for building new inputs
DUMP_REQUEST_DATA = os.getenv("VROBBLER_DUMP_REQUEST_DATA", "false").lower() in TRUTHY

USDA_API_KEY = os.getenv("VROBBLER_USDA_API_KEY")
THESPORTSDB_API_KEY = os.getenv("VROBBLER_THESPORTSDB_API_KEY", "2")
THEAUDIODB_API_KEY = os.getenv("VROBBLER_THEAUDIODB_API_KEY", "2")
PODCASTINDEX_API_KEY = os.getenv("VROBBLER_PODCASTINDEX_API_KEY", "")
PODCASTINDEX_API_SECRET = os.getenv("VROBBLER_PODCASTINDEX_API_SECRET", "")
TMDB_API_KEY = os.getenv("VROBBLER_TMDB_API_KEY", "")
OMDB_API_KEY = os.getenv("VROBBLER_OMDB_API_KEY", "")
LASTFM_API_KEY = os.getenv("VROBBLER_LASTFM_API_KEY")
LASTFM_SECRET_KEY = os.getenv("VROBBLER_LASTFM_SECRET_KEY")
IGDB_CLIENT_ID = os.getenv("VROBBLER_IGDB_CLIENT_ID")
IGDB_CLIENT_SECRET = os.getenv("VROBBLER_IGDB_CLIENT_SECRET")
COMICVINE_API_KEY = os.getenv("VROBBLER_COMICVINE_API_KEY")
BGG_ACCESS_TOKEN = os.getenv("VROBBLER_BGG_ACCESS_TOKEN", "")
DB_BACKUP_SSH_KEY = os.getenv("VROBBLER_DB_BACKUP_SSH_KEY", "")
DB_BACKUP_SSH_DEST = os.getenv("VROBBLER_DB_BACKUP_SSH_DEST", "")
DB_BACKUP_LOCAL_DIR = os.getenv("VROBBLER_DB_BACKUP_LOCAL_DIR", "/var/backups/")
DB_BACKUP_WEBDAV_URL = os.getenv("VROBBLER_DB_BACKUP_WEBDAV_URL", "")
DB_BACKUP_WEBDAV_USER = os.getenv("VROBBLER_DB_BACKUP_WEBDAV_USER", "")
DB_BACKUP_WEBDAV_PASS = os.getenv("VROBBLER_DB_BACKUP_WEBDAV_PASS", "")
DB_BACKUP_WEBDAV_PATH = os.getenv(
    "VROBBLER_DB_BACKUP_WEBDAV_PATH", "var/vrobbler-backups/"
)
DB_BACKUP_NTFY_URL = os.getenv(
    "VROBBLER_DB_BACKUP_NTFY_URL", "https://ntfy.unbl.ink/backups"
)
GEOLOC_ACCURACY = os.getenv("VROBBLER_GEOLOC_ACCURACY", 3)
GEOLOC_PROXIMITY = os.getenv("VROBBLER_GEOLOC_PROXIMITY", "0.0001")
GEOLOC_REVERSE_GEOCODE_RATE = int(
    os.getenv("VROBBLER_GEOLOC_REVERSE_GEOCODE_RATE", "1")
)
GEOLOC_REVERSE_GEOCODE_MAX_RETRIES = int(
    os.getenv("VROBBLER_GEOLOC_REVERSE_GEOCODE_MAX_RETRIES", "8")
)
POINTS_FOR_MOVEMENT_HISTORY = os.getenv("VROBBLER_POINTS_FOR_MOVEMENT_HISTORY", 3)
TODOIST_CLIENT_ID = os.getenv("VROBBLER_TODOIST_CLIENT_ID", "")
TODOIST_CLIENT_SECRET = os.getenv("VROBBLER_TODOIST_CLIENT_SECRET", "")

GOOGLE_API_KEY = os.getenv("VROBBLER_GOOGLE_API_KEY", "")
GOOGLE_AI_API_KEY = os.getenv("VROBBLER_GOOGLE_AI_API_KEY", "")
LICHESS_API_KEY = os.getenv("VROBBLER_LICHESS_API_KEY", "")
OPENROUTER_API_KEY = os.getenv("VROBBLER_OPENROUTER_API_KEY", "")

AGENT_PROVIDER = os.getenv("VROBBLER_AGENT_PROVIDER", "openrouter")
LLM_MODEL = os.getenv("VROBBLER_LLM_MODEL", "openai/gpt-oss-20b:free")
GEMINI_AGENT_MODELS = os.getenv("VROBBLER_GEMINI_AGENT_MODELS", "gemini-3.6-flash")
OPENCODE_CMD = os.getenv("VROBBLER_OPENCODE_CMD", "opencode")

AGENT_PROVIDER_MAX_ATTEMPTS = int(
    os.getenv("VROBBLER_AGENT_PROVIDER_MAX_ATTEMPTS", "3")
)
AGENT_PROVIDER_RETRY_BACKOFF_BASE = int(
    os.getenv("VROBBLER_AGENT_PROVIDER_RETRY_BACKOFF_BASE", "60")
)
AGENT_PROVIDER_RETRY_MAX_BACKOFF = int(
    os.getenv("VROBBLER_AGENT_PROVIDER_RETRY_MAX_BACKOFF", "300")
)

AMAZON_PAAPI_ACCESS_KEY = os.getenv("VROBBLER_AMAZON_PAAPI_ACCESS_KEY", "")
AMAZON_PAAPI_SECRET_KEY = os.getenv("VROBBLER_AMAZON_PAAPI_SECRET_KEY", "")
AMAZON_PAAPI_ASSOCIATE_TAG = os.getenv("VROBBLER_AMAZON_PAAPI_ASSOCIATE_TAG", "")
AMAZON_PAAPI_COUNTRY = os.getenv("VROBBLER_AMAZON_PAAPI_COUNTRY", "US")

FASTCORK_API_KEY = os.getenv("VROBBLER_FASTCORK_API_KEY", "")

DEFAULT_TASK_CONTEXT_TAGS = [
    "Dev",
    "Home",
    "Errand",
    "Blog",
    "Mail",
    "Call",
    "Meeting",
    "Exercise",
]

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "America/New_York")

ALLOWED_HOSTS = ["*"]
CSRF_TRUSTED_ORIGINS = [
    os.getenv(
        "VROBBLER_TRUSTED_ORIGINS",
        "http://localhost:8000",
    ),
    "https://dev-vrobbler.lab.unbl.ink",
]
X_FRAME_OPTIONS = "SAMEORIGIN"

REDIS_URL = os.getenv("VROBBLER_REDIS_URL", None)
if REDIS_URL:
    print(f"Sending tasks to redis@{REDIS_URL.split('@')[-1]}")
else:
    print("Eagerly running all tasks")

CELERY_TASK_ALWAYS_EAGER = os.getenv("VROBBLER_SKIP_CELERY", "false").lower() in TRUTHY
CELERY_BROKER_URL = REDIS_URL if REDIS_URL else "memory://localhost/"
CELERY_RESULT_BACKEND = "django-db"
CELERY_TIMEZONE = os.getenv("VROBBLER_TIME_ZONE", "America/New_York")
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_RESULT_EXTENDED = True
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True

CELERY_TASK_CREATE_MISSING_QUEUES = True
CELERY_TASK_DEFAULT_QUEUE = "default"

# Queue-based prioritization. Interactive/user-facing tasks are routed to a
# dedicated "priority" worker so they never wait behind long-running batch
# jobs. Heavy, scheduled off-peak work goes to a low-concurrency "background"
# worker. Everything not listed here lands on the "default" queue.
CELERY_TASK_ROUTES = {
    # Interactive: user is waiting on the result.
    "scrobbles.tasks.scrobble_agent_session_prompt": {"queue": "priority"},
    "scrobbles.tasks.add_scrobble_to_mopidy_queue": {"queue": "priority"},
    "scrobbles.tasks.add_scrobble_to_mopidy_monthly_playlist": {"queue": "priority"},
    "scrobbles.tasks.add_favorite_to_mopidy_playlist": {"queue": "priority"},
    "scrobbles.tasks.remove_favorite_from_mopidy_playlist": {"queue": "priority"},
    "scrobbles.tasks.reverse_geocode_geolocation": {"queue": "priority"},
    # Per-scrobble chart updates stay on the charts queue so they are not
    # blocked behind scheduled chart rebuilds.
    "scrobbles.tasks.update_charts_for_timestamp": {"queue": "charts"},
    "scrobbles.tasks.build_charts_for_user": {"queue": "charts"},
    # Heavy, scheduled off-peak jobs run on a dedicated low-concurrency worker.
    "scrobbles.tasks.create_yesterdays_charts": {"queue": "background"},
    "scrobbles.tasks.rebuild_weekly_charts": {"queue": "background"},
    "scrobbles.tasks.rebuild_monthly_charts": {"queue": "background"},
    "scrobbles.tasks.rebuild_yearly_charts": {"queue": "background"},
    "scrobbles.tasks.backup_database": {"queue": "background"},
    "scrobbles.tasks.backfill_scrobble_sentiment": {"queue": "background"},
    "scrobbles.tasks.enrich_media_from_webhook": {"queue": "background"},
    "scrobbles.tasks.check_twitch_channels_for_vods": {"queue": "background"},
    "scrobbles.importers.lastfm.dispatch_historical_imports": {"queue": "background"},
    "trends.tasks.compute_all_trends": {"queue": "background"},
    "trends.tasks.compute_user_trends": {"queue": "background"},
    "trends.tasks.compute_single_trend": {"queue": "background"},
}

CELERY_BEAT_SCHEDULE = {
    "build-yesterdays-charts": {
        "task": "scrobbles.tasks.create_yesterdays_charts",
        "schedule": crontab(hour=0, minute=5),
    },
    "rebuild-weekly-charts": {
        "task": "scrobbles.tasks.rebuild_weekly_charts",
        "schedule": crontab(hour=1, minute=0, day_of_week=0),
    },
    "rebuild-monthly-charts": {
        "task": "scrobbles.tasks.rebuild_monthly_charts",
        "schedule": crontab(hour=0, minute=30, day_of_month=1),
    },
    "rebuild-yearly-charts": {
        "task": "scrobbles.tasks.rebuild_yearly_charts",
        "schedule": crontab(hour=0, minute=30, day_of_month=1, month_of_year=1),
    },
    "compute-daily-trends": {
        "task": "trends.tasks.compute_all_trends",
        "schedule": crontab(hour=0, minute=10),
    },
    # ── Crontab replacements ─────────────────────────────────────────────
    "database-backup": {
        "task": "scrobbles.tasks.backup_database",
        "schedule": crontab(hour=2, minute=30),
    },
    "import-from-lastfm": {
        "task": "scrobbles.tasks.import_from_lastfm_all_users",
        "schedule": crontab(minute="*/30"),
    },
    "import-from-webdav": {
        "task": "scrobbles.tasks.import_from_webdav_all_users",
        "schedule": crontab(minute="*/2"),
    },
    # Deprecated: BG Stats files now picked up from WebDAV var/bgstats/
    # "import-from-imap": {
    #     "task": "scrobbles.tasks.import_from_imap_all_users",
    #     "schedule": crontab(minute="*/4"),
    # },
    "import-from-lichess": {
        "task": "scrobbles.tasks.import_from_lichess_all_users",
        "schedule": crontab(minute="*/20"),
    },
    "send-notification-for-in-progress": {
        "task": "scrobbles.tasks.send_notification_for_in_progress",
        "schedule": crontab(minute="*/3"),
    },
    "send-mood-checkin": {
        "task": "scrobbles.tasks.send_mood_checkin",
        "schedule": crontab(hour="*/4", minute=0),
    },
    "send-water-reminder": {
        "task": "scrobbles.tasks.send_water_reminder",
        "schedule": crontab(hour="*/3", minute=0),
    },
    "backfill-scrobble-sentiment": {
        "task": "scrobbles.tasks.backfill_scrobble_sentiment",
        "schedule": crontab(minute="0"),
    },
    "import-from-inaturalist": {
        "task": "nature.tasks.import_from_inaturalist_all_users",
        "schedule": crontab(hour="*/4", minute=30),
    },
}

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    "django.contrib.humanize",
    "django_filters",
    "django_extensions",
    "markdownify",
    "imagekit",
    "storages",
    "taggit",
    "rest_framework.authtoken",
    "oauth2_provider",
    "encrypted_field",
    "profiles",
    "agents",
    "scrobbles",
    "people",
    "charts",
    "trends",
    "videos",
    "music",
    "podcasts",
    "sports",
    "books",
    "boardgames",
    "bricksets",
    "videogames",
    "locations",
    "webpages",
    "tasks",
    "trails",
    "drinks",
    "puzzles",
    "foods",
    "lifeevents",
    "moods",
    "discgolf",
    "birds",
    "nature",
    "workouts",
    "mathfilters",
    "drf_spectacular",
    "rest_framework",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "django_celery_results",
    "mcp_server",
]

SITE_ID = 1

MIDDLEWARE = [
    "vrobbler.health_check.HealthCheckMiddleware",
    "vrobbler.apps.scrobbles.middleware.TimezoneMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.middleware.gzip.GZipMiddleware",
]

ROOT_URLCONF = "vrobbler.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [str(PROJECT_ROOT.joinpath("templates"))],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "videos.context_processors.video_lists",
                "music.context_processors.music_lists",
                "scrobbles.context_processors.now_playing",
                "scrobbles.context_processors.month_color",
                "vrobbler.context_processors.version_info",
            ],
        },
    },
]

MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"

WSGI_APPLICATION = "vrobbler.wsgi.application"

DATABASES = {
    "default": dj_database_url.config(
        default=os.getenv("VROBBLER_DATABASE_URL", "sqlite:///db.sqlite3"),
        conn_max_age=600,
    ),
}

if TESTING:
    DATABASES = {"default": dj_database_url.config(default="sqlite:///testdb.sqlite3")}

db_str = ""
if "sqlite" in DATABASES["default"]["ENGINE"]:
    db_str = f"Connected to sqlite@{DATABASES['default']['NAME']}"
if "postgresql" in DATABASES["default"]["ENGINE"]:
    db_str = f"Connected to postgres@{DATABASES['default']['HOST']}/{DATABASES['default']['NAME']}"
if db_str:
    print(db_str)


CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake",
    }
}
if REDIS_URL:
    CACHES["default"]["BACKEND"] = "django_redis.cache.RedisCache"
    CACHES["default"]["LOCATION"] = REDIS_URL

SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

# We have to ignore content negotiation because Jellyfin is a bad actor
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ],
    "DEFAULT_CONTENT_NEGOTIATION_CLASS": "vrobbler.negotiation.IgnoreClientContentNegotiation",
    "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 200,
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}

SPECTACULAR_SETTINGS = {
    "TITLE": "vrobbler API",
    "DESCRIPTION": "Scrobble everything.",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
    "ENUM_NAME_OVERRIDES": {
        "SportEventTypeEnum": "sports.models.SportEventType.choices",
        "ScrobbleVisibilityEnum": "scrobbles.constants.Visibility.choices",
    },
}

DJANGO_MCP_AUTHENTICATION_CLASSES = [
    "oauth2_provider.contrib.rest_framework.OAuth2Authentication",
    "rest_framework.authentication.TokenAuthentication",
    "rest_framework.authentication.SessionAuthentication",
]
DJANGO_MCP_GET_SERVER_INSTRUCTIONS_TOOL = True

LOGIN_REDIRECT_URL = "/"

AUTH_PASSWORD_VALIDATORS = [
    {
        "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/3.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = os.getenv("VROBBLER_TIME_ZONE", "America/New_York")

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
#
USE_S3_STORAGE = os.getenv("VROBBLER_USE_S3", "False").lower() in TRUTHY

if USE_S3_STORAGE:
    from storages.backends import s3boto3

    AWS_S3_ENDPOINT_URL = os.getenv("AWS_S3_ENDPOINT_URL", "")
    AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME", "")
    AWS_S3_ACCESS_KEY_ID = os.getenv("AWS_S3_ACCESS_KEY_ID")
    AWS_S3_SECRET_ACCESS_KEY = os.getenv("AWS_S3_SECRET_ACCESS_KEY")

    S3_ROOT = "/".join([AWS_S3_ENDPOINT_URL, AWS_STORAGE_BUCKET_NAME])
    print(f"Storing media on S3 at {S3_ROOT}")

    DEFAULT_FILE_STORAGE = "vrobbler.storages.MediaStorage"
    STATICFILES_STORAGE = "vrobbler.storages.StaticStorage"
    STATIC_URL = S3_ROOT + "/static/"
    MEDIA_URL = S3_ROOT + "/media/"

else:
    STATIC_ROOT = os.getenv(
        "VROBBLER_STATIC_ROOT", os.path.join(PROJECT_ROOT, "static")
    )
    MEDIA_ROOT = os.getenv("VROBBLER_MEDIA_ROOT", os.path.join(PROJECT_ROOT, "media"))
    STATIC_URL = os.getenv("VROBBLER_STATIC_URL", "/static/")
    MEDIA_URL = os.getenv("VROBBLER_MEDIA_URL", "/media/")


SCIHUB_DOMAIN = os.getenv("VROBBLER_SCIHUB_DOMAIN", "sci-hub.st")

SKIP_AUTO_EXPANSION_DOWNLOAD = [
    int(x.strip())
    for x in os.getenv("VROBBLER_SKIP_AUTO_EXPANSION_DOWNLOAD", "").split(",")
    if x.strip().isdigit()
]

JSON_LOGGING = os.getenv("VROBBLER_JSON_LOGGING", "false").lower() in TRUTHY
LOG_TYPE = "json" if JSON_LOGGING else "log"

default_level = "INFO"
if DEBUG:
    default_level = "DEBUG"

LOG_LEVEL = os.getenv("VROBBLER_LOG_LEVEL", default_level)
LOG_FILE_PATH = os.getenv("VROBBLER_LOG_FILE_PATH", "/tmp/")

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "root": {
        "handlers": ["console", "file"],
        "level": LOG_LEVEL,
        "propagate": True,
    },
    "formatters": {
        "color": {
            "()": "colorlog.ColoredFormatter",
            # \r returns caret to line beginning, in tests this eats the silly dot that removes
            # the beautiful alignment produced below
            "format": "\r"
            "{log_color}{levelname:8s}{reset} "
            "{bold_cyan}{name}{reset}:"
            "{fg_bold_red}{lineno}{reset} "
            "{thin_yellow}{funcName} "
            "{thin_white}{message}"
            "{reset}",
            "style": "{",
        },
        "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
        "json": {
            "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
            "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "color",
            "level": LOG_LEVEL,
        },
        "null": {
            "class": "logging.NullHandler",
            "level": LOG_LEVEL,
        },
        "sql": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": "".join([LOG_FILE_PATH, "vrobbler_sql.", LOG_TYPE]),
            "formatter": LOG_TYPE,
            "level": LOG_LEVEL,
        },
        "file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": "".join([LOG_FILE_PATH, "vrobbler.", LOG_TYPE]),
            "formatter": LOG_TYPE,
            "level": LOG_LEVEL,
        },
    },
    "loggers": {
        # Quiet down our console a little
        "django": {
            "handlers": ["null"],
            "propagate": True,
        },
        "django.db.backends": {"handlers": ["null"]},
        "django.server": {"handlers": ["null"]},
        "pylast": {"handlers": ["null"], "propagate": False},
        "musicbrainzngs": {"handlers": ["null"], "propagate": False},
        "httpx": {"handlers": ["null"], "propagate": False},
        "vrobbler": {
            "handlers": ["console"],
            "propagate": False,
        },
    },
}

LOG_TO_CONSOLE = os.getenv("VROBBLER_LOG_TO_CONSOLE", "false").lower() in TRUTHY
if LOG_TO_CONSOLE:
    LOGGING["loggers"]["django"]["handlers"] = ["console"]
    LOGGING["loggers"]["vrobbler"]["handlers"] = ["console"]
