# -*- coding: utf-8 -*-
# Django settings for 'www' project.
import os
import uuid

with open('/usr/share/overload/pgaas_db_pass', 'r') as pass_file:
    DB_PASSWORD = pass_file.read().strip()

with open('/etc/yandex/environment.type', 'r') as env_type_file:
    env_type = env_type_file.read().strip()

if os.environ.get('RUNTIME_CLOUD_ENV'):
    RUNTIME_ENV = True
else:
    RUNTIME_ENV = False

DEBUG = False
TEMPLATE_DEBUG = DEBUG

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

ADMIN_ENABLED = False

MANAGERS = ADMINS

DB_HOST = os.environ.get('RUNTIME_CLOUD_MYSQL_HOST', '')
#DB_HOST = os.environ.get('RUNTIME_CLOUD_MYSQL_HOST', 'overload01h.db.yandex.net')
DB_PORT = os.environ.get('RUNTIME_CLOUD_MYSQL_PORT', '6432')

DB_NAME = 'overload'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': DB_NAME,
        'USER': 'overload',
        'PASSWORD': DB_PASSWORD,
        'HOST': DB_HOST,
        'PORT': DB_PORT,
        'OPTIONS': {
            'sslmode': 'require',
        },
        'CONN_MAX_AGE': 49,
    },
}

DATABASE_OPTIONS = {
    "connect_timeout": 60,
}


MEMCACHE_HOST = os.environ.get('RUNTIME_CLOUD_MEMCACHE_HOST', 'kshm03f.yandex.net')
MEMCACHE_PORT = os.environ.get('RUNTIME_CLOUD_MEMCACHE_PORT', '11211')

CLICKHOUSE_HOST = os.environ.get('RUNTIME_CLICKHOUSE_HOST', 'localhost')
CLICKHOUSE_PORT = os.environ.get('RUNTIME_CLICKHOUSE_PORT', '8123')
CLICKHOUSE_USER = 'lunapark'
with open('/usr/share/overload/clickhouse_db_pass', 'r') as secret_file:
    CLICKHOUSE_PWD = secret_file.read().strip()

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

TIME_ZONE = 'Europe/Moscow'

LANGUAGE_CODE = 'en-en'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

MEDIA_ROOT = '/usr/share/overload/media'

MEDIA_URL = ''

STATIC_ROOT = ''
STATIC_URL = '/media/'

with open('/usr/share/overload/overload_secret_key', 'r') as secret_file:
    SECRET_KEY = secret_file.read().strip()

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'csp.middleware.CSPMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
)

ROOT_URLCONF = 'urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/usr/lib/overload/www/templates', 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': (
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.csrf',
                'django.template.context_processors.request',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            )
        }
    },
]

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'social_django',
    'offlinepage',
    'common',
    'api',
    'monitoring',
    'mainpage',
    'onlinepage',
]

LOGGING_CONFIG = None
LOGGING_LEVEL = os.environ.get('LOGGING_LEVEL', 'ERROR')
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'specific': {
            'format': '%(asctime)s %(message)s'
        },
    },
    'handlers': {
        'badman': {
            'level': LOGGING_LEVEL,
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.environ.get('RUNTIME_DJANGO_LOGS_PATH', '/var/log/overload/') + 'default.log',
            'maxBytes': 100 * 1024 ** 2,  # 100 MB
            'backupCount': 0,
            'formatter': 'verbose',
        },
        'clickhouse': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.environ.get('RUNTIME_DJANGO_LOGS_PATH', '/var/log/overload/') + 'clickhouse.log',
            'maxBytes': 1024 ** 3,  # 1 GB
            'backupCount': 0,
            'formatter': 'specific',
        },
    },
    'loggers': {
        'clickhouse': {
            'handlers': ['clickhouse'],
            'level': LOGGING_LEVEL,
        },
    },
    'root': {
        'handlers': ['badman'],
        'level': LOGGING_LEVEL,
    },
}

import logging.config

logging.config.dictConfig(LOGGING)

ADDITIONAL_APPS = []

INSTALLED_APPS.extend(ADDITIONAL_APPS)

ALLOWED_HOSTS = [
    '127.0.0.1',
    '[::1]',
    '93.158.134.96',
    '2a02:6b8::2:96',
    '37.140.188.132',
    '.overload.yandex.net',
    '.overload.yandex.net.',
    'overload.yandex.net',
    'overload.yandex.net.',
    '.overload.n.yandex-team.ru',
    '.overload.n.yandex-team.ru.',
    'overload.n.yandex-team.ru',
    'overload.n.yandex-team.ru.',
    'test-overload.yandex.net'
]

# ===============================================================================
# OAUTH
# ===============================================================================

# SOCIAL_AUTH_USER_MODEL = 'common.UserProfile'

AUTHENTICATION_BACKENDS = (
    'social_core.backends.yandex.YandexOAuth2',
    #     'social_core.backends.linkedin.LinkedinOAuth2',
    #     'social_core.backends.stackoverflow.StackoverflowOAuth2',
    'social_core.backends.github.GithubOAuth2',
    #     'social_core.backends.facebook.FacebookOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/done/'
URL_PATH = ''
#SOCIAL_AUTH_STRATEGY = 'social_core.strategies.django_strategy.DjangoStrategy'
#SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage'
#SOCIAL_AUTH_EMAIL_FORM_HTML = 'email_signup.html'
#SOCIAL_AUTH_EMAIL_VALIDATION_FUNCTION = 'example.app.mail.send_validation'
#SOCIAL_AUTH_EMAIL_VALIDATION_URL = '/email-sent/'
#SOCIAL_AUTH_USERNAME_FORM_HTML = 'username_signup.html'

with open('/usr/share/overload/yandex_oauth_key', 'r') as yandex_oauth_key_file:
    SOCIAL_AUTH_YANDEX_OAUTH2_KEY = yandex_oauth_key_file.read().strip()
with open('/usr/share/overload/yandex_oauth_secret', 'r') as yandex_oauth_secret_file:
    SOCIAL_AUTH_YANDEX_OAUTH2_SECRET = yandex_oauth_secret_file.read().strip()
with open('/usr/share/overload/github_oauth_key', 'r') as github_oauth_key_file:
    SOCIAL_AUTH_GITHUB_KEY = github_oauth_key_file.read().strip()
with open('/usr/share/overload/github_oauth_secret', 'r') as github_oauth_secret_file:
    SOCIAL_AUTH_GITHUB_SECRET = github_oauth_secret_file.read().strip()

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',
    # 'mainpage.pipeline.require_email',
    'social_core.pipeline.mail.mail_validation',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.debug.debug',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
)

SOCIAL_AUTH_DISCONNECT_PIPELINE = (
    'social_core.pipeline.disconnect.get_entries',
    'social_core.pipeline.disconnect.revoke_tokens',
    'social_core.pipeline.disconnect.disconnect'
)

SOCIAL_AUTH_POSTGRES_JSONFIELD = True
SOCIAL_AUTH_JSONFIELD_CUSTOM = 'django.contrib.postgres.fields.JSONField'

# ===============================================================================
# LOCAL SETTINGS
# ===============================================================================

if os.path.exists('/etc/overload_devel'):
    try:
        from local_settings import *
    except ImportError as ie:
        print('Failed to import local_settings module:', ie)
        raise ie

if os.path.exists('/etc/testing'):
    LOGGING['handlers']['badman']['level'] = 'DEBUG'
    LOGGING['root']['level'] = '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 = "'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'", 'data:', 'avatars.githubusercontent.com', 'camo.githubusercontent.com', 'avatars.yandex.net', \
              'avatars.mds.yandex.net', 'yapic.yandex.net', 'mc.yandex.ru'
CSP_CONNECT_SRC = "'self'", 'mc.yandex.ru', 'yastatic.net', 'clck.ru'
CSP_FRAME_SRC = "gitter.im",
CSP_FONT_SRC = "'self'",

# ===============================================================================
# TVM settings
# ===============================================================================

from ticket_parser2.api.v1 import BlackboxClientId
with open('/usr/share/overload/tvm_client_secret', 'r') as pass_file:
    TVM_CLIENT_SECRET = pass_file.read().strip()
TVM_CLIENT_ID = 2011004 if env_type == 'production' else 2010886
TAKEOUT_ID = 2009785 if env_type == 'production' else 2009783
PASSPORT_PROFILE_PROD = 2010646
PASSPORT_PROFILE_TEST = 2010644
BLACKBOX_ID = 222 if env_type == 'production' else 224
BLACKBOX_CLIENT = BlackboxClientId.Prod if env_type == 'production' else BlackboxClientId.Test
BLACKBOX_HOST = os.environ.get('BLACKBOX_HOST', 'blackbox.yandex.net')

# ===============================================================================
# GoZora Proxies Settings
# ===============================================================================

GOZORA_ID = 2023123
GOZORA_USER = 'overload'
GOZORA_TVM = None
PROXIES = {
    'http': 'http://{}:{}@go.zora.yandex.net:1080/'.format(GOZORA_USER, GOZORA_TVM),
    'https': 'http://{}:{}@go.zora.yandex.net:1080/'.format(GOZORA_USER, GOZORA_TVM),
}
VERIFY_SSL = False
