# -*- coding: utf-8 -*-
# type: ignore
from __future__ import annotations

import os
from pathlib import Path

from keep_it_secret.ext.loader import load_secrets

from hotpocket_backend.secrets.base import BaseSecrets
from hotpocket_common.constants import App, Env

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

DEBUG = False
TESTING = False
ALLOWED_HOSTS = []

ENV = Env(os.getenv('HOTPOCKET_BACKEND_ENV', None))
APP = App(os.getenv('HOTPOCKET_BACKEND_APP', None))

HOTPOCKET_BACKEND_SECRETS_PACKAGE = os.getenv(
    'HOTPOCKET_BACKEND_SECRETS_PACKAGE', 'hotpocket_backend.secrets',
)

SECRETS: BaseSecrets = load_secrets(
    HOTPOCKET_BACKEND_SECRETS_PACKAGE, ENV.value, APP.value,
)

SECRET_KEY = SECRETS.SECRET_KEY

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'social_django',

    'hotpocket_backend.apps.admin.HotPocketAdminConfig',
    'hotpocket_backend.apps.core',

    'hotpocket_backend.apps.accounts',
    'hotpocket_backend.apps.bot',
    'hotpocket_backend.apps.htmx',
    'hotpocket_backend.apps.saves',
    'hotpocket_backend.apps.ui',
]

MIDDLEWARE = [
]

ROOT_URLCONF = None

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'hotpocket_backend.apps.accounts.context_processors.auth_settings',
                'hotpocket_backend.apps.accounts.context_processors.hotpocket_oidc',
                'hotpocket_backend.apps.ui.context_processors.site_title',
                'hotpocket_backend.apps.ui.context_processors.image_tag',
                'hotpocket_backend.apps.ui.context_processors.request_id',
                'hotpocket_backend.apps.ui.context_processors.htmx',
                'hotpocket_backend.apps.ui.context_processors.debug',
                'hotpocket_backend.apps.ui.context_processors.version',
                'hotpocket_backend.apps.ui.context_processors.appearance_settings',
                'hotpocket_backend.apps.ui.context_processors.operator_email',
            ],
        },
    },
]

WSGI_APPLICATION = 'hotpocket_backend.wsgi.application'

STORAGES = {
    'default': {
        'BACKEND': 'django.core.files.storage.FileSystemStorage',
    },
    'staticfiles': {
        'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage',
    },
}

DATABASES = {
    'default': {
        'ENGINE': SECRETS.DATABASE.engine,
        'NAME': SECRETS.DATABASE.name,
        'USER': SECRETS.DATABASE.user,
        'PASSWORD': SECRETS.DATABASE.password,
        'HOST': SECRETS.DATABASE.host,
        'PORT': SECRETS.DATABASE.port,
    },
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = 'static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGGING_LEVEL = os.environ.get('HOTPOCKET_BACKEND_LOGGING_LEVEL', 'INFO')

LOG_FORMAT = '%(asctime)s %(levelname)s [%(name)s] [%(request_id)s] (%(funcName)s:%(lineno)s) %(message)s'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'request_id': {
            '()': 'hotpocket_backend.apps.core.logging_utils.RequestIDFilter',
        },
    },
    'formatters': {
        'verbose': {
            'format': LOG_FORMAT,
            'style': '%',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'filters': ['request_id'],
            'formatter': 'verbose',
        },
        'hotpocket': {
            'class': 'logging.StreamHandler',
            'filters': ['request_id'],
            'formatter': 'verbose',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'WARNING',
    },
    'loggers': {
        'hotpocket_backend': {
            'handlers': ['hotpocket'],
            'level': LOGGING_LEVEL,
            'propagate': False,
        },
        'hotpocket_common': {
            'handlers': ['hotpocket'],
            'level': LOGGING_LEVEL,
            'propagate': False,
        },
        'hotpocket_soa': {
            'handlers': ['hotpocket'],
            'level': LOGGING_LEVEL,
            'propagate': False,
        },
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        '': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
    },
}

DEFAULT_EMAIL_FROM = os.getenv(
    'HOTPOCKET_BACKEND_DEFAULT_EMAIL_FROM',
    'noreply@hotpocket.work.bthlabs.net',
)
SERVER_EMAIL = os.getenv(
    'HOTPOCKET_BACKEND_SERVER_EMAIL',
    'backend@hotpocket.work.bthlabs.net',
)

AUTH_USER_MODEL = 'accounts.Account'

LOGIN_REDIRECT_URL = '/'

SITE_TITLE = 'HotPocket by BTHLabs'

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

AUTHENTICATION_BACKENDS = [
    'hotpocket_backend.apps.accounts.backends.AccessTokenBackend',
]

IMAGE_ID = os.getenv('HOTPOCKET_BACKEND_IMAGE_ID', 'development.00000000')

MODEL_AUTH_IS_DISABLED = (
    os.getenv('HOTPOCKET_BACKEND_MODEL_AUTH_IS_DISABLED', 'false').lower() == 'true'
)
if MODEL_AUTH_IS_DISABLED is False:
    AUTHENTICATION_BACKENDS.append(
        'django.contrib.auth.backends.ModelBackend',
    )

SOCIAL_AUTH_JSONFIELD_ENABLED = True
SOCIAL_AUTH_URL_NAMESPACE = 'sso'
SOCIAL_AUTH_PIPELINE = [
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    # 'social_core.pipeline.mail.mail_validation',
    'social_core.pipeline.social_auth.associate_by_email',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
    'hotpocket_backend.apps.accounts.social.set_user_is_staff',
    'hotpocket_backend.apps.accounts.social.set_user_is_superuser',
]

SOCIAL_AUTH_HOTPOCKET_OIDC_OIDC_ENDPOINT = SECRETS.OIDC.endpoint
SOCIAL_AUTH_HOTPOCKET_OIDC_KEY = SECRETS.OIDC.key
SOCIAL_AUTH_HOTPOCKET_OIDC_SECRET = SECRETS.OIDC.secret
SOCIAL_AUTH_HOTPOCKET_OIDC_SCOPE = SECRETS.OIDC.scope

if SECRETS.OIDC.is_enabled is True:
    AUTHENTICATION_BACKENDS.append(
        'hotpocket_backend.apps.accounts.social.HotPocketOpenIdConnectAuth',
    )

CRISPY_ALLOWED_TEMPLATE_PACKS = 'bootstrap5'
CRISPY_TEMPLATE_PACK = 'bootstrap5'

CELERY_BROKER_URL = SECRETS.CELERY.broker_url
CELERY_RESULT_BACKEND = SECRETS.CELERY.result_backend
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True
CELERY_ENABLE_UTC = True
CELERY_RESULT_EXTENDED = True
CELERY_TASK_ROUTES = {
    'celery.*': 'celery',
    'hotpocket_backend.*': 'webapp',
}
CELERY_BEAT_SCHEDULE = {
}
CELERY_EMAIL_TASK_CONFIG = {
    'queue': 'hotpocket',
}
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
CELERY_WORKER_LOG_FORMAT = LOG_FORMAT  # noqa: F405
CELERY_WORKER_TASK_LOG_FORMAT = (
    '%(asctime)s %(levelname)s [%(name)s] (%(funcName)s:%(lineno)s) '
    '[%(task_name)s(%(task_id)s)] %(message)s'
)
CELERY_TASK_IGNORE_RESULT = (
    os.environ.get('HOTPOCKET_BACKEND_CELERY_IGNORE_RESULT', 'false').lower() == 'true'
)
CELERY_TASK_ALWAYS_EAGER = (
    os.environ.get('HOTPOCKET_BACKEND_CELERY_ALWAYS_EAGER', 'false').lower() == 'true'
)
CELERY_TASK_EAGER_PROPAGATES = True

HOTPOCKET_BOT_STRATEGY = 'hotpocket_backend.apps.bot.strategy.basic:BasicStrategy'
HOTPOCKET_BOT_BANNED_HOSTNAMES = [
    # YT returns dummy data when I try to fetch the page and extract
    # metadata. I'd have to use Google APIs for that and it's 11:30 PM...
    'youtube.com',
    'youtu.be',
    # Reddit's response is too generic to pull any useful info from it.
    # Since they forced Apollo to shut down, I refuse to even think about
    # interacting with their API :P.
    'reddit.com',
    # Twitter, amirite?
    'twitter.com',
    't.co',
    'x.com',
]

SAVES_SAVE_ADAPTER = os.environ.get(
    'HOTPOCKET_BACKEND_SAVES_SAVE_ADAPTER',
    'hotpocket_backend.apps.saves.adapters.basic:BasicSaveAdapter',
)
SAVES_ASSOCIATION_ADAPTER = os.environ.get(
    'HOTPOCKET_BACKEND_SAVES_ASSOCIATION_ADAPTER',
    'hotpocket_backend.apps.saves.adapters.basic:BasicAssociationAdapter',
)

UPLOADS_PATH = None

SITE_SHORT_TITLE = 'HotPocket'

OPERATOR_EMAIL = os.environ.get('HOTPOCKET_BACKEND_OPERATOR_EMAIL', None)
