import json
import os
import sys
import yenv

import datasources_config_wrapper
from django_pgaas import HostManager
from django_replicated.settings import *  # noqa
from intranet.search.settings.app_settings import APP_NAME, ISEARCH  # noqa

conf = datasources_config_wrapper.DatasourcesConfigWrapper(prefix='intrasearch', fallback_on_env_vars=True)
IN_DEPLOY = 'DEPLOY_BOX_ID' in os.environ

DEBUG = bool(int(os.environ.get('ISEARCH_DEBUG', 1)))

TEMPLATE_DEBUG = DEBUG

SECRET_KEY = '%zqeu*w)0)5w#kt^0^j$2%m)^n1$-xh15(japsgrk0*=8ha)w#'
ENCRYPTION_PASSWORD = conf.ecnryption_password[:32] if conf.ecnryption_password else SECRET_KEY

AUTH_USER_MODEL = 'users.User'
TIME_ZONE = 'Europe/Moscow'
DEFAULT_LANGUAGE = 'ru'
LANGUAGE_CODE = 'ru-ru'
SITE_ID = 1
MEDIA_ROOT = ''
MEDIA_URL = ''

MIDDLEWARE = [
    'django.middleware.common.CommonMiddleware',
    'django_replicated.middleware.ReplicationMiddleware',
]

APPEND_SLASH = False

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',

    'intranet.search.core',
    'intranet.search.core.users',
    'django_pgaas',
]

DDF_VALIDATE_ARGS = True

LOGGING_CONFIG = None

# нам нужны дефолтные поля, которые приходят из django_yauth

SERVICES_API_TOKEN = 'isearch'

ALLOWED_HOSTS = ['.yandex.net', '.yandex-team.ru', '.intrasearch', '*']

DATABASE_CONN_MAX_AGE = int(os.environ.get('ISEARCH_DATABASE_CONN_MAX_AGE', 30))

if IN_DEPLOY:
    pg_hosts_list = json.loads(conf.pg_hosts_list)
else:
    pg_hosts_list = conf.pg_hosts_list
manager = HostManager(pg_hosts_list or [])

DATABASES = {
    'default': {
        'ENGINE': 'django_pgaas.backend',
        'HOST': manager.host_string,
        'NAME': conf.pg_name,
        'USER': conf.pg_user,
        'PASSWORD': conf.pg_password,
        'PORT': conf.pg_port,
        'CONN_MAX_AGE': DATABASE_CONN_MAX_AGE,
        'DISABLE_SERVER_SIDE_CURSORS': True,
        'OPTIONS': {
            'connect_timeout': 2,
            'target_session_attrs': 'read-write',
        }
    },
    'slave': {
        'ENGINE': 'django_pgaas.backend',
        'HOST': manager.host_string,
        'NAME': conf.pg_name,
        'USER': conf.pg_user,
        'PASSWORD': conf.pg_password,
        'PORT': conf.pg_port,
        'CONN_MAX_AGE': DATABASE_CONN_MAX_AGE,
        'DISABLE_SERVER_SIDE_CURSORS': True,
        'OPTIONS': {
            'connect_timeout': 2,
            'target_session_attrs': 'any',
        },
    }
}

REPLICATED_DATABASE_SLAVES = ['slave']
DATABASE_ROUTERS = ['django_replicated.router.ReplicationRouter']

# Mongo & ylock

if IN_DEPLOY:
    mongo_db3_hosts_list = json.loads(conf.mongo_db3_hosts_list)
else:
    mongo_db3_hosts_list = conf.mongo_db3_hosts_list
ISEARCH_MONGODB_HOSTS = mongo_db3_hosts_list or ['mongodb']
ISEARCH_MONGODB_DB = conf.mongo_db3_dbname or 'isearch'
ISEARCH_MONGODB_USER = conf.mongo_db3_user
ISEARCH_MONGODB_PASSWORD = conf.mongo_db3_password
ISEARCH_MONGODB_RS = conf.mongo_db3_rs
ISEARCH_MONGODB_CACHE_COLLECTION_PREFIX = 'cache'

ISEARCH_MONGODB_URI = 'mongodb://{hosts}/{dbname}?replicaSet={rs}'.format(
    hosts=','.join(ISEARCH_MONGODB_HOSTS),
    dbname=ISEARCH_MONGODB_DB,
    rs=ISEARCH_MONGODB_RS,
)

YLOCK = {
    'backend': 'mongodb',
    'prefix': 'isearch',
    'hosts': ISEARCH_MONGODB_HOSTS,
    'db_name': ISEARCH_MONGODB_DB,
    'username': ISEARCH_MONGODB_USER,
    'password': ISEARCH_MONGODB_PASSWORD,
    'mechanism': 'DEFAULT',
}

# глубина кластера в вики фасете
ISEARCH_WIKI_CLUSTER_FACET_DEPTH = 5

# очередь для таски удаления локальных статусов
ISEARCH_CLEANUP_DIRECT_QUEUE_NAME = 'swarm@%(hostname)s.dq'

ISEARCH_REDIS_UNIX_SOCKET_PATH = '/var/run/yandex/intrasearch/redis/general.sock'

INDEXATION_STATS_REDIS = {
    'unix_socket_path': ISEARCH_REDIS_UNIX_SOCKET_PATH,
    'db': 2
}

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'local_redis': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'unix://%s?db=1' % ISEARCH_REDIS_UNIX_SOCKET_PATH,
        'TIMEOUT': 60,
        'OPTIONS': {
            'IGNORE_EXCEPTIONS': True,
        },
    },
    'local_memcached': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

ISEARCH_CA_CERTS = '/etc/ssl/certs/ca-certificates.crt'

# name и get-параметры запроса из надметапоиска, которые мы не хотим логировать
ISEARCH_ABOVEMETA_NO_LOG = {
    'auth': ['sessionid', 'userip', 'ts_sign']
}

ISEARCH_OAUTH = {}
if IN_DEPLOY:
    for key, value in os.environ.items():
        if key.startswith('intrasearch_oauth'):
            key_substr = key[len('intrasearch_'):]
            ISEARCH_OAUTH[key_substr] = value
else:
    ISEARCH_OAUTH = conf.oauth or {}

TVM2_CLIENT_NAME = 'isearch'
if IN_DEPLOY:
    TVM2_CLIENT_ID = ISEARCH['tvm']['clients']['source']['app_id']
    TVM2_SECRET = conf.tvm_client_secret
    TVM2_DSTS = [item['alias'] for item in ISEARCH['tvm']['clients']['destinations']]
    TVM2_AUTH_TOKEN = os.environ.get('TVMTOOL_LOCAL_AUTHTOKEN')
else:
    try:
        TVM2_CONFIG = json.loads(os.environ.get('QLOUD_TVM_CONFIG'))
    except (ValueError, TypeError):
        TVM2_CONFIG = {'clients': {TVM2_CLIENT_NAME: {}}}

    TVM2_CLIENT_ID = TVM2_CONFIG['clients'][TVM2_CLIENT_NAME].get('self_tvm_id')
    TVM2_SECRET = TVM2_CONFIG['clients'][TVM2_CLIENT_NAME].get('secret')
    TVM2_DSTS = list(TVM2_CONFIG['clients'][TVM2_CLIENT_NAME].get('dsts', {}))
    TVM2_AUTH_TOKEN = os.environ.get('QLOUD_TVM_TOKEN')

TVM2_USER_HEADER = 'X-Ya-User-Ticket'
TVM2_SERVICE_HEADER = 'X-Ya-Service-Ticket'
TVM2_WEREWOLFING_IDS = json.loads(conf.werewolfing_tvm_ids) if conf.werewolfing_tvm_ids else []
TVM2_WEREWOLFING_USER_LOGIN = conf.werewolfing_user_login if conf.werewolfing_user_login else 'robot-isearch-nobody'
TVM2_WEREWOLFING_USER_UID = conf.werewolfing_user_uid if conf.werewolfing_user_uid else '1120000000550791'
TVM2_WEREWOLFING_STAFF_ID = json.loads(conf.werewolfing_user_staff_id) if conf.werewolfing_user_staff_id else 379394
TVM2_WEREWOLFING_USER_OFFICE = 1  # Morozov
TVM2_WEREWOLFING_USER_FLOOR = 4  # Why not?
TVM2_WEREWOLFING_GROUPS = json.loads(conf.tvm2_werewolfing_groups) if conf.tvm2_werewolfing_groups else []
# groups = [{
#   "group": {
#       "url": "meow",
#       "id": 1635,
#   }
# }]

ISEARCH_CA_BUNDLE = '/etc/ssl/certs/ca-certificates.crt'
ISEARCH_TOKEN_EXPIRES = 14  # in days
ISEARCH_SLUG_IN_DIRECTORY = 'search'

ISEARCH_MAIN_STAFF_GROUP = 962

ISEARCH_AVAILABLE_TOP_LEVEL_DOMAINS = [
    'yandex-team.ru',
    'yandex.ru',
    'yandex.com',
    'yandex.net',

    # Для разработки
    'localhost',
    'abovemeta',
]

ISEARCH_VALID_INDEXATION_TIMEOUT = 2  # in hours

BASE_LOCAL_PATH = '/intrasearch/translations/locale'
if yenv.type == 'development':
    arc_path = sys.executable[:sys.executable.index('intranet/search')]
    BASE_LOCAL_PATH = os.path.join(arc_path, 'intranet/search/translations')
else:
    BASE_LOCAL_PATH = '/intrasearch/translations/locale'


LOCALE_PATHS = (
    BASE_LOCAL_PATH,
)

ISEARCH_SAAS_KPS_PREFIX = os.environ.get('ISEARCH_SAAS_KPS_PREFIX') or ''

ISEARCH_YT_PROXY = os.environ.get('ISEARCH_YT_PROXY') or ''

ISEARCH_DOCUMENT_STORAGES = os.environ.get('ISEARCH_DOCUMENT_STORAGES', 'logbroker').split(',')

ISEARCH_SSH_KEY_PATH = os.environ.get('SSH_KEY_PATH') or '/etc/yandex/intrasearch_robot'
ISEARCH_SSH_LOGIN = os.environ.get('SSH_LOGIN') or 'zomb-prj-213'

ISEARCH_ENABLE_SCOPE_PERMISSIONS = os.environ.get('ISEARCH_ENABLE_SCOPE_PERMISSIONS') == '1'

# список очередей трекера, из которых мы не индексируем тикеты
ISEARCH_TRACKER_QUEUES_BLACKLIST = os.environ.get('ISEARCH_TRACKER_QUEUES_BLACKLIST', '').split(',')
