import logging

from typing import Optional
from async_clients.clients.webmaster import Client as WebmasterClient

from intranet.domenator.src.settings import config
from .tvm2 import get_service_ticket
from intranet.domenator.src.domenator_logging.middleware.profiling_client import ProfilingClientMixin


log = logging.getLogger(__name__)


class WebmasterProfilingClient(WebmasterClient, ProfilingClientMixin):
    CLIENT_NAME = 'webmaster'


async def get_webmaster_client() -> WebmasterProfilingClient:
    return WebmasterProfilingClient(
        host=config.webmaster_host,
        service_ticket=await get_service_ticket(config.webmaster_tvm2_client)
    )


async def get_domain_info_with_fallback(name: str, admin_id: str) -> dict:
    webmaster = await get_webmaster_client()

    info = await webmaster.info(
        domain=name,
        admin_uid=admin_id,
        ignore_errors='USER__HOST_NOT_ADDED'
    )
    # Если в webmaster-е нет такого домена, значит либо он удалился по таймауту,
    # либо пользователь сам удалил его через интерфейс webmaster-а
    # Надо добавить домен и снова запросить инфо
    if not info.get('data'):
        await webmaster.add(
            domain=name,
            admin_uid=admin_id,
        )
        info = await webmaster.info(
            domain=name,
            admin_uid=admin_id,
        )
    return info


def _get_preferred_host(info: dict) -> Optional[str]:
    preferred_host = info.get('request', {}).get('domainVerificationState', {}).get('preferredHost')
    if preferred_host:
        # выдача там вида http:www.aite-dev1.yaconnect.com:80
        try:
            return preferred_host.split(':')[1]
        except IndexError:
            log.warning(f'Key error while parsing preferredHost: {preferred_host}')


async def get_domain_ownership_info(name: str, admin_id: str) -> tuple:

    webmaster = await get_webmaster_client()

    info = await get_domain_info_with_fallback(name=name, admin_id=admin_id)

    data = info['data']
    verification_status = data.get('verificationStatus')

    preferred_host = _get_preferred_host(info=info)
    status = None
    last_check = None

    if verification_status in ('IN_PROGRESS', 'VERIFIED'):
        status = 'in-progress'

    verification_uin = data['verificationUin']
    methods = await webmaster.list_applicable(
        domain=name,
        admin_uid=admin_id,
    )

    # Если в ответе есть информация про последнюю попытку проверки,
    # то прокинем её в наш собственный ответ
    if 'lastVerificationAttemptTime' in data:
        last_check = {
            'date': data['lastVerificationAttemptTime'],
            'method': 'webmaster.' + data['verificationType'].lower(),
        }

        if 'lastVerificationFailInfo' in data:
            last_check['fail_type'] = data['lastVerificationFailInfo'].get('type', 'unknown').lower()
            if 'reason' in data['lastVerificationFailInfo']:
                last_check['fail_reason'] = data['lastVerificationFailInfo'].get('reason', 'unknown').lower()
    methods = [
        {
            'method': 'webmaster.' + method.lower(),
            'weight': 0,
            'code': verification_uin,
        }
        for method in methods
    ]

    return status, methods, last_check, preferred_host, verification_status
