import logging

from dataclasses import dataclass, asdict
from typing import List, Optional

from saas.library.python.api_mixins.json_api import JsonAPI, JsonAPIException


@dataclass(frozen=True)
class AlertTemplate:
    key: str
    owners: List[str]
    content: str


class GolovanAlertAPI(JsonAPI):
    class Endpoint:
        CREATE = 'create'
        GET = 'get'
        UPDATE = 'update'
        APPLY = 'apply'

        RENDER_JSON = 'render_json'
        RENDER_TEXT = 'render_text'

    def create_or_update_template(self, template: AlertTemplate) -> any:
        json_params: dict = asdict(template)

        try:
            return self._make_request('post', self.Endpoint.UPDATE,
                                      params={'key': template.key}, json_params=json_params)
        except JsonAPIException as exc:
            if exc.error == GolovanAlertAPIError.NOT_FOUND:
                logging.info('Template %s does not exist, trying to create a new one', template.key)
                return self._make_request('post', self.Endpoint.CREATE, json_params=json_params)
            else:
                raise exc

    @staticmethod
    def _is_error_response(response_data: any) -> bool:
        return isinstance(response_data, dict) and response_data.get('status') == 'error'

    @staticmethod
    def _get_error_from_response_data(response_data) -> Optional[str]:
        return response_data.get('error_code')

    def apply_template(self, template: AlertTemplate) -> any:
        return self._make_request('post', f'{self.Endpoint.APPLY}/{template.key}')

    def render_new_json_template(self, template: AlertTemplate) -> any:
        return self._make_request('post', f'{self.Endpoint.RENDER_JSON}/{template.key}', data=template.content)


class GolovanAlertAPIError:
    NOT_FOUND = 'not_found'


golovan_alert_api: GolovanAlertAPI = GolovanAlertAPI(base_url='https://yasm.yandex-team.ru/srvambry/tmpl/alerts')
