"""Monitor maxwell process and restart/alert as needed."""

import logging
import subprocess

from logging.handlers import SMTPHandler

import requests

MAXWELL_ENDPOINT = "http://localhost:<%= node['maxwell']['monitor']['metrics_http_port'] %>/healthcheck"


def restart_maxwell_service():
    """Restart <%= node['maxwell']['service_name'] %> systemd service."""
    command = ['/usr/bin/systemctl',
               'restart',
               "<%= node['maxwell']['service_name'] %>"
               ]
    try:
        subprocess.call(command, shell=False)
    except Exception as error:
        logging.error('Could not restart process: %r', error)

mail_handler = SMTPHandler(
    mailhost="<%= node['maxwell']['monitor']['mailhost'] %>",
    fromaddr="<%= node['maxwell']['monitor']['fromaddr'] %>",
    toaddrs=["<%= node['maxwell']['monitor']['toaddrs'] %>"],
    subject="<%= node['maxwell']['service_name'] %> Error"
)

logging.basicConfig(level=logging.INFO)

mail_handler.setLevel(logging.ERROR)
mail_handler.setFormatter(logging.Formatter(
    '[%(asctime)s] %(levelname)s: %(message)s'
))

logger = logging.getLogger()
logger.addHandler(mail_handler)

try:
    resp = requests.get(MAXWELL_ENDPOINT)

    health = resp.json()
    if health['MaxwellHealth']['healthy'] is True:
        print("i am so healthy")
    else:
        logger.critical('Maxwell failed healthchecks. Restarting...')
        restart_maxwell_service()
except Exception as requests_error:
    logger.critical('Cannot connect to Maxwell http interface. Restarting...')
    restart_maxwell_service()
