# -*- coding: utf-8 -*-
import os
import uuid
import logging.config

from django_pgaas import HostManager
from django_yauth.settings import *


# TODO: move to pathlib.Path(__file__).parent.parent after moving on py3
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Django settings
DEBUG = True

ADMINS = (('Lunapark Dev Team', 'load@yandex-team.ru'), )
MANAGERS = ADMINS

TIME_ZONE = 'Europe/Moscow'
LANGUAGE_CODE = 'ru-ru'
SITE_ID = 1
USE_I18N = True
USE_L10N = False

CERT_FILE = '/usr/local/share/ca-certificates/Yandex/YandexInternalRootCA.crt'

ROOT_URLCONF = 'urls'

# Static
STATIC_ROOT = ''
STATIC_URL = '/static/'

MEDIA_ROOT = BASE_DIR + '/media'

ALLOWED_HOSTS = [
    '127.0.0.1',
    'lunapark.localhost'
]

# Templates
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR + '/www/templates', 'templates'],
        'APP_DIRS': False,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.csrf',
                'django.template.context_processors.request',
                'django_yauth.context.yauth',
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
            'debug': DEBUG,
        },
    }
]

# DJANGO_CSP
CSP_SCRIPT_NONCE = uuid.uuid4().hex
CSP_STYLE_NONCE = uuid.uuid4().hex
CSP_DEFAULT_SRC = "'none'",
# TODO: unsafe-eval нужен только для библиотеки underscore.js из-за нее же много тэгов script используются как темплейты
#       есть смысл избавиться от underscore.js
CSP_SCRIPT_SRC = "'self'", "'unsafe-eval'", "'nonce-{}'".format(CSP_SCRIPT_NONCE), 'mc.yandex.ru', \
                 'social.yandex.ru', 'yastatic.net'
# Инлайн стили везде. И в темплейтах, и в библиотеках, и даже в яндексовом шрифте. Поэтому никак не подключить nonce
CSP_STYLE_SRC = "'self'", "'unsafe-inline'", 'yastatic.net'
CSP_IMG_SRC = "'self'", 'center.yandex-team.ru', 'data:', 'mc.yandex.ru'
CSP_CONNECT_SRC = "'self'", 'mc.yandex.ru', 'yastatic.net', 'c.yandex-team.ru', 'nda.ya.ru'
CSP_FONT_SRC = "'self'",

INSTALLED_APPS = [
    'django_yauth',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'django_template_common',
    'projectpage',
    'regression',
    'offlinepage',
    'firestarter',
    'comparepage',
    'taskpage',
    'django_pgaas',
    'common',
    'api',
    'rest_framework',
    'mobilepage',
    'mobilecompare',
    'mobileregression',
    'mobilefirestarter',
    'monitoring',
    'mainpage',
    'onlinepage',
]

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'csp.middleware.CSPMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django_yauth.middleware.YandexAuthTestMiddleware',
)

# ENV variables
DB_HOST = os.environ.get('DB_HOST', 'lunaparkdb-load01f.db.yandex.net')
DB_PASSWORD = os.environ.get('DB_PWD', '')
OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN', '')
PLATFORM_TOKEN = os.environ.get('PLATFORM_TOKEN', '')
STORAGE_AMMO_KEY = os.environ.get('STORAGE_AMMO_KEY', '')
STORAGE_ARTEFACT_KEY = os.environ.get('STORAGE_ARTEFACT_KEY', '')
SECRET_KEY = os.environ.get('SECRET_KEY', '')
CLICKHOUSE_HOST = os.environ.get('CLICKHOUSE_HOST', '')
CLICKHOUSE_PORT = os.environ.get('CLICKHOUSE_PORT', '')
CLICKHOUSE_USER = os.environ.get('CLICKHOUSE_USER', '')
CLICKHOUSE_PWD = os.environ.get('CLICKHOUSE_PWD', '')
TVM2_SECRET_STARTREK = os.environ.get('TVM2_SECRET_STARTREK', '')
REDIS_HOST = os.environ.get('REDIS_HOST', 'sas-xxcxaae0scdjvc5y.db.yandex.net'),
REDIS_PORT = os.environ.get('REDIS_PORT', 6379)
REDIS_SENTINEL_PORT = os.environ.get('REDIS_SENTINEL_PORT', 26379)
REDIS_DB_NAME = os.environ.get('REDIS_DB_NAME', 7)
REDIS_DB_PWD = os.environ.get('REDIS_PWD', '')
SANDBOX_OAUTH_TOKEN = os.environ.get('SANDBOX_OAUTH_TOKEN', '')

# External urls
NANNY_TANKS_URL = 'https://nanny.yandex-team.ru/v2/services/production_yandex_tank/current_state/instances/'
CONDUCTOR_TANKS_URL = 'https://c.yandex-team.ru/api-cached/generator/lunapark_tanks'
GOLEM_SOURCE_URL = 'http://ro.admin.yandex-team.ru/api/host_query.sbml?hostname={}&columns=short_line'
CONDUCTOR_SOURCE_URL = 'https://c.yandex-team.ru/api-cached/generator/get_dc?fqdn={}'
QLOUD_INT_SOURCE_URL = 'https://qloud.yandex-team.ru/api/container/{}'
QLOUD_EXT_SOURCE_URL = 'https://qloud-ext.yandex-team.ru/api/container/{}'
PLATFORM_SOURCE_URL = 'https://platform.yandex-team.ru/api/container/{}'
GENCFG_API_URL = 'http://api.gencfg.yandex-team.ru/trunk/hosts_data'
MDS_UPLOAD_URL = 'http://storage-int.mds{}.yandex.net:1111/upload-{}/{}'
MDS_GET_URL = 'https://storage-int.mds{}.yandex.net/get-{}/{}'
MDS_GET_ARTEFACT_URL = 'http://storage-int.mdst.yandex.net:80/get-load-artefact/{}'
BLACKBOX_URL = 'http://blackbox.yandex-team.ru/blackbox'
VALIDATOR_URL = 'https://tank-validator.yandex-team.ru/config/validate?fmt={}'

# Postgres settings
DB_NAME = 'lunaparkdb_load'
DB_PORT = 6432
DB_HOSTS = [
    ('lunaparkdb-load01e.db.yandex.net', 'iva'),
    ('lunaparkdb-load01f.db.yandex.net', 'myt'),
    ('lunaparkdb-load01i.db.yandex.net', 'man'),
]
DATABASE_OPTIONS = {
    "connect_timeout": 60,
}
DB_PGAAS_HOST = HostManager(DB_HOSTS).host_string
DATABASES = {
    'default': {
        'ENGINE': 'django_pgaas.backend',
        'HOST': DB_PGAAS_HOST,
        'PORT': DB_PORT,
        'USER': 'lunapark',
        'PASSWORD': DB_PASSWORD,
        'NAME': DB_NAME,
        'OPTIONS': {
            'sslmode': 'require',
            'target_session_attrs': 'read-write'
        },
        'CONN_MAX_AGE': 49,
    },
    'slave': {
        'ENGINE': 'django_pgaas.backend',
        'HOST': DB_PGAAS_HOST,
        'PORT': DB_PORT,
        'USER': 'lunapark',
        'PASSWORD': DB_PASSWORD,
        'NAME': DB_NAME,
        'OPTIONS': {'target_session_attrs': 'any'},
    },
}

# Memcache
MEMCACHE_HOST = os.environ.get('MEMCACHE_HOST', 'kshm03f.yandex.net')
MEMCACHE_PORT = os.environ.get('MEMCACHE_PORT', '11211')

# Logging
LOGGING_CONFIG = None
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(pathname)s %(lineno)s %(message)s'
        },
        'specific': {
            'format': '%(asctime)s %(message)s'
        },
    },
    'handlers': {
        'badman': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '/var/log/lunapark/django/default.log',
            'maxBytes': 100 * 1024 ** 2,  # 100 MB
            'backupCount': 0,
            'formatter': 'verbose',
            'encoding': 'utf-8'
        },
    },
    'root': {
        'handlers': ['badman'],
        'level': 'DEBUG',
    },
}
logging.config.dictConfig(LOGGING)

# Yauth
YAUTH_PASSPORT_FIELDS = [blackbox.FIELD_LOGIN, blackbox.FIELD_EMAIL, blackbox.FIELD_LANGUAGE]
YAUTH_TYPE = 'intranet'
YAUTH_TEST_USER = 'lunapark'
YAUTH_USE_SITES = False
YAUTH_USE_TVM2_FOR_BLACKBOX = True
YAUTH_TVM2_CLIENT_ID = 2000352
YAUTH_TVM2_SECRET = os.environ.get('YAUTH_TVM2_SECRET', '')
TVM_ID = os.environ.get('TVM_ID', 2023037)
BLACKBOX_TVM_ID = os.environ.get('BLACKBOX_TVM_ID', 223)
YAV_OAUTH_TOKEN = os.environ.get('YAV_OAUTH_TOKEN', '')

# DJANGO REST
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
    'ORDERING_PARAM': 'order_by'
}
