###################################################################################
# ocr_translate - a django app to perform OCR and translation of images.          #
# Copyright (C) 2023-present Davide Grassano                                      #
#                                                                                 #
# This program is free software: you can redistribute it and/or modify            #
# it under the terms of the GNU General Public License as published by            #
# the Free Software Foundation, either version 3 of the License.                  #
#                                                                                 #
# This program is distributed in the hope that it will be useful,                 #
# but WITHOUT ANY WARRANTY; without even the implied warranty of                  #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                   #
# GNU General Public License for more details.                                    #
#                                                                                 #
# You should have received a copy of the GNU General Public License               #
# along with this program.  If not, see {http://www.gnu.org/licenses/}.           #
#                                                                                 #
# Home: https://github.com/Crivella/ocr_translate                                 #
###################################################################################
"""
Django settings for ocr_translate project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
# pylint: skip-file
import json
import os
from pathlib import Path

from ocr_translate.plugin_manager import PluginManager

PMNG = PluginManager()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(os.getenv('OCT_BASE_DIR', ''))
PROJECT_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '').lower() in ['true', 't', '1', 'yes', 'y']
DJANGO_LOG_LEVEL = os.environ.get('DJANGO_LOG_LEVEL', 'INFO').upper()

STREAM_HANDLER = 'logging.StreamHandler'
STREAM_HANDLER_KWARGS = {}
MEDIUM_FMT_STR = '{asctime} - {levelname:>7s} - {name:>15s}:{module:<15s} - {message}'

try:
    from rich.logging import RichHandler
except:
    pass
else:
    STREAM_HANDLER = 'rich.logging.RichHandler'
    STREAM_HANDLER_KWARGS = {
        'rich_tracebacks': True,
        'tracebacks_suppress': ['django', 'logging', 'rich'],
    }
    MEDIUM_FMT_STR = '{message}'

LOGFILE = os.environ.get('OCT_LOGFILE', '')

handlers_list = ['console']
file_handler = {}
if LOGFILE:
    if LOGFILE.lower() in ['true', 't', '1', 'yes', 'y']:
        LOGFILE = BASE_DIR / 'ocr_translate.log'
    file_handler = {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LOGFILE.as_posix(),
            'formatter': 'verbose',
            'maxBytes': 10*1024*1024,  # 10 MB
            'backupCount': 5,
            'encoding': 'utf8',
        }
    }
    handlers_list.append('file')

def skip_static_requests(record):
    return not record.args[0].startswith('GET /static/')

# Logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} - {asctime} - {module}:{funcName}:{lineno} - {process:d} - {thread:d} - {message}',
            'style': '{',
            },
        'medium': {
            'format': MEDIUM_FMT_STR,
            'style': '{',
            },
        'simple': {
            'format': '{levelname} - {message}',
            'style': '{',
            },
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
        'skip_static_requests': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': skip_static_requests,
        }
    },
    'handlers': {
        'console': {
            'level': DJANGO_LOG_LEVEL,
            'class': STREAM_HANDLER,
            'formatter': 'medium',
            **STREAM_HANDLER_KWARGS,
        },
        **file_handler
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': False,
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'ERROR',
            'filters': ['skip_static_requests'],
            'propagate': False,
        },
        'ocr.general': {
            'handlers': handlers_list,
            'level': 'DEBUG',
            'propagate': False,
        },
        'ocr.worker': {
            'handlers': handlers_list,
            'level': 'DEBUG',
            'propagate': False,
        },
        'plugin': {
            'handlers': handlers_list,
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

def parse_list(s, sep=';'):
    if s.startswith('"') and s.endswith('"'):
        s = s[1:-1]
    if s.startswith("'") and s.endswith("'"):
        s = s[1:-1]
    return list(filter(None, s.split(sep)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-7h+*^e963rdi*2jbdlhqvmg%xnx$9@s*ccgcfae@t219$#!)vu')

ALLOWED_HOSTS = ['localhost', '127.0.0.1']
ALLOWED_HOSTS += parse_list(os.environ.get('DJANGO_ALLOWED_HOSTS', ''))

###################################################################################
# CORS
USE_CORS_HEADERS = os.environ.get('USE_CORS_HEADERS', 'false').lower() in ['true', 't', '1', 'yes', 'y']
CORS_ALLOWED_ORIGINS = parse_list(os.environ.get('CORS_ALLOWED_ORIGINS', ''))
CSRF_TRUSTED_ORIGINS = CORS_ALLOWED_ORIGINS
if 'CORS_ALLOW_METHODS' in os.environ:
    CORS_ALLOW_METHODS = parse_list(os.environ.get('CORS_ALLOW_METHODS', ''))
if 'CORS_ALLOW_HEADERS' in os.environ:
    CORS_ALLOW_HEADERS = parse_list(os.environ.get('CORS_ALLOW_HEADERS', ''))

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
if USE_CORS_HEADERS:
    INSTALLED_APPS.append('corsheaders')
INSTALLED_APPS.append('ocr_translate')
INSTALLED_APPS += PMNG.all_plugins

# Middleware
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
]
if USE_CORS_HEADERS:
    MIDDLEWARE.append('corsheaders.middleware.CorsMiddleware')
MIDDLEWARE += [
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ocr_translate.app.urls'

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

WSGI_APPLICATION = 'ocr_translate.app.wsgi.application'


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

DATABASE_ENGINE = os.environ.get('DATABASE_ENGINE', 'django.db.backends.sqlite3')
DATABASE_NAME = os.environ.get('DATABASE_NAME', os.path.join(PROJECT_DIR, 'db.sqlite3'))

DATABASE = {
    'ENGINE': DATABASE_ENGINE,
    'NAME': DATABASE_NAME,
}

for k in ['USER', 'PASSWORD', 'HOST', 'PORT']:
    if not os.environ.get('DATABASE_' + k) is None:
        DATABASE[k] = os.environ.get('DATABASE_' + k)

OPTIONS = {}
if DATABASE_ENGINE == 'django.db.backends.mysql':
    # https://stackoverflow.com/questions/2108824/mysql-incorrect-string-value-error-when-save-unicode-string-in-django
    OPTIONS['charset'] = 'utf8mb4'

if DATABASE_ENGINE == 'django.db.backends.sqlite3':
    ptr = {}
    DATABASE['OPTIONS'] = ptr
    ptr['init_command'] = 'PRAGMA journal_mode=wal;'

DATABASES = {
    'default': DATABASE
}


# Password validation
# https://docs.djangoproject.com/en/4.2/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',
    },
]


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DATA_UPLOAD_MAX_MEMORY_SIZE = 10*1024*1024

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

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'static'),
    )
STATIC_ROOT = os.path.join(PROJECT_DIR, 'staticfiles')
# MEDIA_URL = '/media/'
# MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
