import os

from typing import Dict

from django.conf import settings
from tvm2 import TVM2

if os.getenv('IS_ARCADIA'):
    from tvmauth import BlackboxTvmId as BlackboxClientId
else:
    from ticket_parser2_py3.api.v1 import BlackboxClientId


class TVM2Error(Exception):
    pass


def get_tvm_client() -> TVM2:
    return TVM2(
        client_id=settings.FEMIDA_TVM_CLIENT_ID,
        secret=settings.FEMIDA_TVM_SECRET,
        blackbox_client=BlackboxClientId.ProdYateam,
        destinations=settings.TVM_DESTINATIONS,
        allowed_clients=settings.YAUTH_TVM2_ALLOWED_CLIENT_IDS,
    )


def get_service_ticket(client_id: int) -> str:
    """
    Получает один сервисный TVM-тикет
    :param client_id: int
    :return: str
    """
    service_tickets = get_service_tickets(client_id)
    return service_tickets.get(client_id)


def get_service_tickets(*client_ids: int) -> Dict[int, str]:
    """
    Получает одним запросом несколько сервисных TVM-тикетов
    :param client_ids: tuple(int)
    :return: {int: str} - словарь client_id: ticket
    """
    client_ids = map(str, client_ids)
    tvm_client = get_tvm_client()
    service_tickets = tvm_client.get_service_tickets(*client_ids)
    service_tickets = {int(k): v for k, v in service_tickets.items()}
    if not list(service_tickets.values()).pop():
        # если хотя бы один тикет не получен - все значения возвращаются None
        raise TVM2Error('Failed to get TVM service tickets')
    return service_tickets


def get_user_ticket(request) -> str:
    ticket_in_request = request.META.get(settings.YAUTH_TVM2_USER_HEADER)
    if ticket_in_request:
        return ticket_in_request

    tvm_client = get_tvm_client()

    params = request.yauser.authenticated_by.extract_params(request)
    session_id = params.get('session_id')
    oauth_token = params.get('oauth_token')

    if not session_id and not oauth_token:
        raise TVM2Error('Failed to get session_id or oauth_token from request')

    user_ticket = tvm_client.get_user_ticket(
        user_ip=params.get('userip'),
        server_host=params.get('server_host'),
        oauth_token=oauth_token,
        session_id=session_id,
    )
    if not user_ticket:
        raise TVM2Error('Failed to get TVM user ticket from Blackbox')
    return user_ticket


def get_robot_user_ticket() -> str:
    tvm_client = get_tvm_client()
    user_ticket = tvm_client.get_user_ticket(
        user_ip='127.0.0.1',
        server_host=settings.FEMIDA_HOST,
        oauth_token=settings.FEMIDA_ROBOT_TOKEN,
    )
    if not user_ticket:
        raise TVM2Error('Failed to get TVM user ticket by robot token from Blackbox')
    return user_ticket
