import aiohttp
import json
import logging

from saas.tools.devops.canary.reader.core.common import DocReader, DocumentCheckFailed


class KVDocReader(DocReader):
    async def _check_document(self, endpoint: str, text: str) -> None:
        logging.info('Checking document #%s [%s, %s, %s]', text, self._service.name, self._service.ctype, endpoint)

        url = f'http://{endpoint}'
        headers = {'X-Ya-Service-Ticket': self._tvm_client.get_service_ticket(self._service.ctype)}
        params = {
            'hr': 'json',
            'ms': 'proto',
            'normal_kv_report': 'true',
            'service': self._service.name,
            'sp_meta_search': 'multi_proxy',
            'text': text,
        }

        async with aiohttp.ClientSession(headers=headers) as session:
            async with session.get(url, params=params) as response:
                response.raise_for_status()
                response_text = await response.text()

                logging.debug(
                    'Response for %s: %s %s [%s, %s, %s]',
                    url, response_text, response.status, self._service.name, self._service.ctype, endpoint
                )

        response_data = json.loads(response_text)
        if response_data['TotalDocCount'] == [0, 0, 0]:
            raise DocumentCheckFailed(error=DocReader.Error.DOCUMENT_NOT_FOUND)
