# -*- encoding: utf-8 -*-

import environ
import logging
from pathlib import Path

from django.utils import timezone

log = logging.getLogger(__name__)

VERSION = "0.3.4"

# BASE_DIR is the root of the project, all paths should be constructed from it using pathlib
BASE_DIR = Path(__file__).parent.parent


# region Env Vars

# Create an environment and read variables from .env file
env = environ.Env(DEBUG=(bool, True))
environ.Env.read_env(BASE_DIR / ".env")

required_env_vars = (
    "BOT_TOKEN", "DISCORD_KEY", "DISCORD_SECRET", "DISCORD_REDIRECT_URL",
    "DISCORD_OAUTH2_URL", "SUPERUSER_IDS"
)

for var in required_env_vars:
    if not env(var, default=None):
        log.warning("Required environment variable %s is not set, the application will fail!", var)


# region Security

# SECURITY WARNING: This is sensitive data, keep secure!
SECRET_KEY = env('SECRET_KEY', default="unsecure-default-secret-key")

# SECURITY WARNING: Must be 'False' in production!
DEBUG = env('DEBUG')

# Hosts and Origins that the server host must be within.
ALLOWED_HOSTS = ["localhost", "127.0.0.1", "pyrss-website", env("HOST", default="127.0.0.1")]
CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://127.0.0.1", "http://pyrss-website", "https://" + env("HOST", default="127.0.0.1")]


# region App definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    "rest_framework.authtoken",
    "django_filters",
    "compressor",
    'apps.api',
    'apps.home',
    'apps.authentication',
    "apps.health",
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'core.urls'
APPEND_SLASH = True

LOGIN_URL = "/login/"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

AUTH_USER_MODEL = "authentication.DiscordUser"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "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',
                "apps.context_processors.cfg_client_id"
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'


# region Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DB_ENGINE = env("DB_ENGINE", default=None)

if not DB_ENGINE:
    db_data = {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": "db.sqlite3"
    }
else:
    db_data = {
        "ENGINE": env("DB_ENGINE"),
        "NAME": env("DB_NAME"),
        "USER": env("DB_USER"),
        "PASSWORD": env("DB_PASS"),
        "HOST": env("DB_HOST"),
        "PORT": env("DB_PORT")
    }

DATABASES = { "default": db_data }

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

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" }
]

AUTHENTICATION_BACKENDS = [
    "apps.authentication.backends.DiscordAuthenticationBackend"
]

# region Discord Settings

BOT_TOKEN = env("BOT_TOKEN", default=None)
DISCORD_KEY = env("DISCORD_KEY", default=None)
DISCORD_SECRET = env("DISCORD_SECRET", default=None)
DISCORD_SCOPES = env("DISCORD_SCOPES", default="identity,guilds").split(",")  # ["identify", "guilds"]
DISCORD_CODE_EXCHANGE_REQUEST = {
    "headers": {"Content-Type": "application/x-www-form-urlencoded"},
    "data": {
        "client_id": DISCORD_KEY,
        "client_secret": DISCORD_SECRET,
        "grant_type": "authorization_code",
        "redirect_uri": env("DISCORD_REDIRECT_URL", default=None),
        "scope": " ".join(DISCORD_SCOPES),
        "code": ""
    }
}
DISCORD_REFRESH_TOKEN_REQUEST = {
    "headers": {"Content-Type": "application/x-www-form-urlencoded"},
    "data": {
        "grant_type": "refresh_token",
        "refresh_token": ""
    }
}
DISCORD_API_URL = env("DISCORD_API_URL", default="https://discord.com/api/v10")
DISCORD_OAUTH2_URL = env("DISCORD_OAUTH2_URL", default=None)
SUPERUSER_IDS = env("SUPERUSER_IDS", default="").split(",")

# region Logging
# https://docs.djangoproject.com/en/5.0/topics/logging/

LOGGING_DIR = BASE_DIR / "logs"
LOGGING_DIR.mkdir(exist_ok=True)
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': LOGGING_DIR / f'{timezone.now()}.log',
            "formatter": "verbose",
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            "formatter": "verbose"
        },
        "timed_file": {
            "level": "DEBUG",
            "class": "logging.handlers.TimedRotatingFileHandler",
            "when": "D",
            "interval": 1,
            "backupCount": 3,
            "encoding": "UTF-8",
            "filename": LOGGING_DIR / "debug.log",
            "formatter": "verbose"
        }
    },
    'loggers': {
        "apps": {
            "handlers": ["timed_file", "console"],
            "level": "DEBUG",
            "propagate": True
        },
        "django": {
            "handlers": ["timed_file", "console"],
            "level": "INFO",
            "propagate": True
        },
        "django.request": {
            "handlers": ["timed_file", "console"],
            "level": "ERROR",
            "propagate": True
        }
    },
    "formatters": {
        "verbose": {
            "format": "[%(asctime)s] [%(levelname)s] [%(name)s]: %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        }
    }
}


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

LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_TZ = True


# region Static files
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_ROOT = BASE_DIR / "staticfiles"
STATIC_URL = "/static/"
STATICFILES_DIRS = (BASE_DIR / "static",)  # Extra places for collectstatic to find static files.
STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "compressor.finders.CompressorFinder",
)

# region SASS Compression

COMPRESS_ENABLED = True
COMPRESS_OFFLINE = not env("DEBUG")
COMPRESS_PRECOMPILERS = [("text/x-scss", "django_libsass.SassCompiler")]
COMPRESS_CSS_FILTERS = ["compressor.filters.css_default.CssAbsoluteIdentifier"]
LIBSASS_ADDITIONAL_INCLUDE_PATHS = [str(BASE_DIR / "static/bootstrap-5.3.3/scss")]


# region Media Files

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'


# region Rest Framework
# https://www.django-rest-framework.org/

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '10000/hour'
    },
    'DEFAULT_RENDERER_CLASSES': [
        'apps.api.renderers.FixedJSONRenderer',
        # 'rest_framework.renderers.AdminRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer'
    ],
    "EXCEPTION_HANDLER": "apps.api.exceptions.conflict_exception_handler"
}


# region Data logic

MAX_SUBSCRIPTIONS_PER_SERVER = env("MAX_SUBSCRIPTIONS_PER_SERVER", default=15)
MAX_FILTERS_PER_SERVER = env("MAX_FILTERS_PER_SERVER", default=15)
MAX_MESSAGE_STYLES_PER_SERVER = env("MAX_MESSAGE_STYLES_PER_SERVER", default=15)
MAX_CHANNELS_PER_SUBSCRIPTION = env("MAX_CHANNELS_PER_SUBSCRIPTION", default=5)
