import logging

from typing import Dict, Tuple

from saas.library.python.saas_alerts.golovan import golovan_alert_api, AlertTemplate
from saas.tools.devops.saas_disaster_alerts.disaster_alerts.modules.config import DisasterAlertsConfig
from saas.tools.devops.saas_disaster_alerts.disaster_alerts.modules.services import get_and_process_services
from saas.tools.devops.saas_disaster_alerts.disaster_alerts.modules.warden import WardenManager


def create_or_update_alerts(
    config: DisasterAlertsConfig,
    replace_remote: bool = False,
    apply_remote: bool = False
):
    logging.info('Re-generating *.macros file for services')

    warden_manager: WardenManager = WardenManager(config.warden_component_name)
    services_cnt: int = get_and_process_services(config, warden_manager, replace_remote)

    logging.info('Found and processed %d services', services_cnt)
    if not services_cnt:
        logging.info('Skipping next steps, because there are no corresponding services')
        return

    if replace_remote:
        logging.info('Creating remote templates from *.macros and other template files')

        template_keys: Tuple[str, str, str] = (
            config.alerts_macros_template_key,
            config.services_template_key,
            config.alerts_template_key,
        )
        template_key_to_template: Dict[str, AlertTemplate] = {}

        for template_key in template_keys:
            with open(config.get_template_file_path(template_key), 'r', encoding='utf-8') as f:
                content: str = f.read()
            template: AlertTemplate = AlertTemplate(key=template_key, owners=config.owners, content=content)
            template_key_to_template[template.key] = template

            try:
                golovan_alert_api.create_or_update_template(template)
            except Exception as exc:
                logging.error('Unable to create or update template %s', template.key)
                raise exc
            else:
                logging.info('Template %s has been created or updated', template.key)

        if apply_remote:
            logging.info('Deleting unvisited warden functionalities')
            warden_manager.delete_unvisited_functionalities()

            alerts_template: AlertTemplate = template_key_to_template[config.alerts_template_key]

            logging.info('Applying template %s', alerts_template.key)
            golovan_alert_api.apply_template(alerts_template)

    logging.info('Done')
