import datetime

import pytz
from typing import Set
from .celery_beat import CELERY_BEAT_SCHEDULE_BASE

from asgi_yauth.settings import AsgiYauthConfig


class Settings(AsgiYauthConfig):
    ENV_TYPE: str = 'default'
    DEBUG: bool = True

    POSTGRES_DATABASE: str = 'watcher'
    POSTGRES_USER: str = 'watcher'
    POSTGRES_PASSWORD: str = 'watcher'
    POSTGRES_HOSTS: str = 'localhost'
    POSTGRES_HOST: str = 'localhost'  # алиас на мастер
    POSTGRES_PORT: int = 5432

    @property
    def db_settings(self):
        return {
            'database': self.POSTGRES_DATABASE,
            'user': self.POSTGRES_USER,
            'password': self.POSTGRES_PASSWORD,
            'connect_args': {
                'host': self.POSTGRES_HOSTS,
                'port': self.POSTGRES_PORT,
                'target_session_attrs': 'read-write',
            }
        }

    @property
    def database_url(self):
        db_settings = self.db_settings.copy()
        db_settings['connect_args'] = '&'.join(
            f'{k}={v}' for k, v in db_settings['connect_args'].items()
        )
        return 'postgresql://{user}:{password}@/{database}?{connect_args}'.format(
            **db_settings
        )

    ROBOT_UID = '1120000000352974'
    ROBOT_LOGIN = 'robot-duty-watcher'
    ROBOT_TOKEN: str = 'fake_robot_oauth_token'

    tvm2_client: str = '2027880'
    tvm2_allowed_clients: list = ['*']
    TVM_SERVICES: dict = {
        'abc': 2012192,
        'jns': 2029080,
        'gozora': 2023123,
        # 'passport': 223,
        'staff-api': 2001976,
        # 'intrasearch': 2001037,
        # 'idm': 2001600,
    }

    DOCS_PREFIX: str = '/api/watcher/docs'
    UNISTAT_PATH: str = '/api/watcher/common/unistat/'
    PING_PATH: str = '/api/watcher/common/ping'

    STAFF_SYNC_INTERVAL = 30  # на сколько дней вперед стафф синкает данные

    STAFF_API_HOST: str = 'https://staff-api.test.yandex-team.ru/'
    STAFF_HOST: str = 'https://staff.test.yandex-team.ru/'
    JNS_API_HOST: str = 'https://jns.yandex-team.ru/'
    ABC_API_HOST: str = 'https://abc-back.test.yandex-team.ru/'

    LOCKS_ENABLED: bool = True
    YLOCK_TOKEN: str = 'fake_token'
    YQL_OAUTH_TOKEN: str = 'fake_yql_token'

    JNS_PROJECT = 'Watcher-test'
    JNS_PROBLEM_NOBODY_ON_DUTY = 'duty_problem_nobody_on_duty'
    JNS_PROBLEM_STAFF_HAS_GAP = 'duty_problem_staff_has_gap'
    JNS_START_SHIFT_TEMPLATE = 'duty_start_notification'
    JNS_START_SHIFT_SOON_TEMPLATE = 'duty_start_notification_soon'

    ABC_HOST = 'abc.test.yandex-team.ru'
    ABC_MIGRATION_SHIFT_START_DATE = '2022-01-01'
    ABC_MIGRATION_SHIFT_END_DATE_DELTA = 180

    BOT_KEY = 'watcher-test'
    BOT_TOKEN: str
    BOT_USE_LOCKS: bool = False
    BOT_USE_GOZORA: bool = True
    BOT_WORKERS: int = 1
    GOZORA_CLIENT_ID = 'watcher_test'
    GOZORA_URL: str = 'http://go.zora.yandex.net:1080'

    @property
    def ylock_config(self):
        return {
            'backend': 'yt',
            'prefix': f'//home/watcher/{self.ENV_TYPE}',
            'token': self.YLOCK_TOKEN,
            'connect_timeout': 3,
        }

    TASKS_DEFAULT_COUNTDOWN: int = 5  # секунд
    TASKS_MIN_LOCK_TIME: int = 5  # секунд

    CELERY_BROKER_TRANSPORT_OPTIONS: dict = {
        'is_secure': False,
        'region': 'yandex',
        'visibility_timeout': 60 * 60  # 1 час
    }
    CELERY_BROKER_URL: str = 'sqs://sqs.yandex.net:8771'
    CELERY_WORKER_HIJACK_ROOT_LOGGER: bool = False

    LOGBROKER_TOKEN: str
    LOGBROKER_PORT: int = 2135
    LOGBROKER_ABC_TOPIC: str
    LOGBROKER_ABC_CONSUMER: str
    LOGBROKER_ENDPOINTS: list = [
        'sas.logbroker.yandex.net',
        'iva.logbroker.yandex.net',
        'vla.logbroker.yandex.net',
    ]

    DEFAULT_TIMEZONE = pytz.timezone('Europe/Moscow')

    CELERY_TIMEZONE = pytz.timezone('Europe/Moscow')

    UTC = pytz.timezone('UTC')

    ALLOWED_TVM_CLIENT_FOR_UID_HEADER: Set[int] = {2018742, 2012192}

    CA_ROOT_PATH: str = '/etc/ssl/certs/ca-certificates.crt'

    X_SECRET_HASH: str = 'fake_one'

    ENABLE_TASK_QUEUE: bool = True

    DEFAULT_COLLATION = 'en_US'

    LOG_CONTEXT_ENABLE_HTTP_TRACKING: bool = True
    LOG_CONTEXT_ENABLE_DB_TRACKING: bool = True
    LOG_CONTEXT_SLOW_SQL: int = 3
    LOG_CONTEXT_RESPONSE_MAX_SIZE: int = 0
    LOG_CONTEXT_ENABLE_STACKTRACES: bool = False
    LOG_CONTEXT_ENABLE_HTTP_400_WARNING: bool = True
    LOG_CONTEXT_ALLOWED_HEADERS: list = []

    LOG_CONTEXT_PROVIDERS = [
        'watcher.logic.logger.provider.request',
        'watcher.logic.logger.provider.auth',
    ]

    SHIFT_START_TIMEDELTA = datetime.timedelta(minutes=30)
    SHIFT_FINISH_TIMEDELTA = datetime.timedelta(hours=1)

    UNISTAT_SCHEDULE_THRESHOLD_MULTIPLIER = 0.9
    UNISTAT_SCHEDULE_MAX_RECALCULATION_TIME = datetime.timedelta(minutes=5)

    YT_DUMP_EVENTS_MAX_PORTION = 5000

    CELERY_BEAT_SCHEDULE = CELERY_BEAT_SCHEDULE_BASE

    NOTIFY_STAFF = False

    class Config:
        env_prefix = ''
