import threading
import logging
from typing import Dict

from django.conf import settings
from django.http import JsonResponse

from staff.lib import requests

logger = logging.getLogger('monitoring.taxi_credentials')

TAXI_AUTH_URL = 'https://business.taxi.yandex.ru/api/1.0/client/{0}/'


def check_taxi_credentials(skip_logins=None):
    skip_logins = skip_logins or []
    result = dict.fromkeys(settings.TAXI_API_CREDENTIALS)
    threads = []

    def add_check_taxi_account(organization, oauth_token, client_id):
        try:
            response = requests.get(
                url=TAXI_AUTH_URL.format(client_id),
                headers={'Authorization': oauth_token},
                timeout=(1, 3, 5),
            )
            response_data = response.json()
            result[organization] = {
                'response_status': response.status_code,
                'client_id_check': 'OK' if response_data.get('_id') == client_id else 'Fail',
                # 'response_body': response_data,
            }
        except Exception as exc:
            result[organization] = {'exception': str(exc)}

    for org_name, taxi_api_credentials in settings.TAXI_API_CREDENTIALS.items():
        client_login = taxi_api_credentials['login']
        if client_login in skip_logins:
            continue

        oauth_token = taxi_api_credentials['oauth_token']
        client_id = taxi_api_credentials['client_id']

        threads.append(
            threading.Thread(
                target=add_check_taxi_account,
                kwargs={
                    'organization': org_name,
                    'oauth_token': oauth_token,
                    'client_id': client_id
                }
            )
        )

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    return result


def find_failed_taxi_credentials(check_results) -> Dict:
    failed_results = {
        org_name: check_data
        for org_name, check_data in check_results.items()
        if not check_data.get('client_id_check') == 'OK'
    }
    return failed_results


def check_taxi_api_auth(request):
    skip_logins = request.GET.get('skip_logins', '').split(',')
    show_all = bool(request.GET.get('show_all', False))

    check_results = check_taxi_credentials(skip_logins=skip_logins)
    if show_all:
        return JsonResponse(data=check_results)

    failed_results = find_failed_taxi_credentials(check_results)

    if failed_results:
        logger.info('Failed taxi credentials: %s', list(failed_results.keys()))
    return JsonResponse(data=failed_results)
