# coding=utf-8

from typing import cast

import requests

from ..Monitors.monitor import Monitor
from .alerter import Alerter, AlertLength, AlertType, register


@register
class SMS77Alerter(Alerter):
    """Send SMS alerts using the sms77 service."""

    alerter_type = "sms77"

    def __init__(self, config_options: dict) -> None:
        super().__init__(config_options)
        self.api_key = cast(
            str, self.get_config_option("api_key", required=True, allow_empty=False)
        )
        self.target = cast(
            str, self.get_config_option("target", required=True, allow_empty=False)
        )

        self.sender = cast(str, self.get_config_option("sender", default="SmplMntr"))
        if len(self.sender) > 11:
            self.alerter_logger.warning("truncating SMS sender name to 11 chars")
            self.sender = self.sender[:11]

        self.support_catchup = True

    def send_alert(self, name: str, monitor: Monitor) -> None:
        """Send an SMS alert."""

        if not monitor.urgent:
            return

        alert_type = self.should_alert(monitor)
        if alert_type not in [AlertType.FAILURE, AlertType.SUCCESS]:
            return

        message = self.build_message(AlertLength.SMS, alert_type, monitor)

        url = "https://gateway.sms77.io/api"
        params = {"text": message, "to": self.target, "from": self.sender}

        if not self._dry_run:
            try:
                r = requests.get(url, params=params, auth=("basic", self.api_key))
                s = r.text
                if not s.startswith("100"):
                    self.alerter_logger.error("Unable to send SMS: status code %s", s)
            except Exception:
                self.alerter_logger.exception("SMS sending failed")
        else:
            self.alerter_logger.info("dry_run: would send SMS: %s", message)

    def _describe_action(self) -> str:
        return "SMSing {target} via SMS77".format(target=self.target)

@@ -1303,16 +1303,20 @@
 7.io/api
+/sms
 %22%0A      
@@ -1327,16 +1327,29 @@
 rams = %7B
+%0A            
 %22text%22: 
@@ -1356,16 +1356,28 @@
 message,
+%0A           
  %22to%22: s
@@ -1387,16 +1387,28 @@
 .target,
+%0A           
  %22from%22:
@@ -1419,16 +1419,57 @@
 f.sender
+,%0A            %22p%22: self.api_key,%0A        
 %7D%0A%0A     
@@ -1565,38 +1565,8 @@
 rams
-, auth=(%22basic%22, self.api_key)
 )%0A  

Fix SMS77 Alerter api key parameter and URL