#!/usr/bin/env python3
# xMatters
# Bulk: no
#
# The extensionless filename is intentional: Checkmk uses it as the method name.
# Copyright (C) 2026 Everbridge, Inc.
# SPDX-License-Identifier: GPL-2.0-only
"""Send a normalized Checkmk notification to an xMatters Flow Designer trigger."""

from __future__ import annotations

import base64
import http.client
import json
import os
import re
import socket
import ssl
import sys
from dataclasses import dataclass
from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple
from urllib import error, parse, request

EXIT_SUCCESS = 0
EXIT_TEMPORARY = 1
EXIT_FINAL = 2

DEFAULT_TIMEOUT_SECONDS = 30.0
MAX_RESPONSE_BYTES = 2048
TEMPORARY_HTTP_STATUS_CODES = frozenset((408, 425, 429))
USER_AGENT = "xmatters-checkmk-notification/1.0.0"

ERROR_PREFIX = "Unable to send Checkmk notification."
REQUIRED_TRIGGER_ERROR = f"{ERROR_PREFIX} 'Trigger URL' cannot be null or empty."
INVALID_TRIGGER_ERROR = f"{ERROR_PREFIX} Trigger URL is invalid."
TEMPORARY_ERROR = (
    f"{ERROR_PREFIX} The Flow Designer trigger could not be reached. "
    "Checkmk should retry delivery."
)

HOST_PAYLOAD_FIELDS = {
    "name": "HOSTNAME",
    "alias": "HOSTALIAS",
    "address": "HOSTADDRESS",
    "state": "HOSTSTATE",
    "previous_state": "LASTHOSTSTATE",
    "previous_hard_state": "PREVIOUSHOSTHARDSTATE",
    "output": "HOSTOUTPUT",
    "long_output": "LONGHOSTOUTPUT",
    "perfdata": "HOSTPERFDATA",
    "check_command": "HOSTCHECKCOMMAND",
    "problem_id": "HOSTPROBLEMID",
    "last_problem_id": "LASTHOSTPROBLEMID",
    "notification_number": "HOSTNOTIFICATIONNUMBER",
    "attempt": "HOSTATTEMPT",
    "max_attempts": "MAXHOSTATTEMPTS",
    "downtime_depth": "HOSTDOWNTIME",
    "acknowledgement_author": "HOSTACKAUTHOR",
    "acknowledgement_comment": "HOSTACKCOMMENT",
    "groups": "HOSTGROUPNAMES",
    "contact_groups": "HOSTCONTACTGROUPNAMES",
    "notes": "HOSTNOTES",
    "notes_url": "HOSTNOTESURL",
}

SERVICE_PAYLOAD_FIELDS = {
    "description": "SERVICEDESC",
    "display_name": "SERVICEDISPLAYNAME",
    "state": "SERVICESTATE",
    "previous_state": "LASTSERVICESTATE",
    "previous_hard_state": "PREVIOUSSERVICEHARDSTATE",
    "output": "SERVICEOUTPUT",
    "long_output": "LONGSERVICEOUTPUT",
    "perfdata": "SERVICEPERFDATA",
    "check_command": "SERVICECHECKCOMMAND",
    "problem_id": "SERVICEPROBLEMID",
    "last_problem_id": "LASTSERVICEPROBLEMID",
    "notification_number": "SERVICENOTIFICATIONNUMBER",
    "attempt": "SERVICEATTEMPT",
    "max_attempts": "MAXSERVICEATTEMPTS",
    "downtime_depth": "SERVICEDOWNTIME",
    "acknowledgement_author": "SERVICEACKAUTHOR",
    "acknowledgement_comment": "SERVICEACKCOMMENT",
    "groups": "SERVICEGROUPNAMES",
    "contact_groups": "SERVICECONTACTGROUPNAMES",
    "notes": "SERVICENOTES",
    "notes_url": "SERVICENOTESURL",
}

CONTACT_PAYLOAD_FIELDS = {
    "name": "CONTACTNAME",
    "alias": "CONTACTALIAS",
    "email": "CONTACTEMAIL",
    "pager": "CONTACTPAGER",
    "contacts": "CONTACTS",
}


class ConfigurationError(ValueError):
    """A final notification configuration error."""


class PasswordStoreError(ConfigurationError):
    """A final password-store lookup error."""


class NoRedirectHandler(request.HTTPRedirectHandler):
    """Return redirect responses to the caller instead of following them."""

    def redirect_request(self, req, fp, code, msg, headers, newurl):  # type: ignore[no-untyped-def]
        return None


@dataclass(frozen=True)
class HttpResult:
    status_code: int
    body: bytes


def collect_context(environment: Optional[Mapping[str, str]] = None) -> Dict[str, str]:
    """Collect Checkmk NOTIFY_* variables without retaining their prefix."""
    source = os.environ if environment is None else environment
    return {
        name[len("NOTIFY_") :]: value
        for name, value in source.items()
        if name.startswith("NOTIFY_")
    }


def _value(context: Mapping[str, str], key: str) -> str:
    return context.get(key, "")


def _selected_value(
    context: Mapping[str, str],
    host_key: str,
    service_key: str,
) -> str:
    return _value(context, service_key if _value(context, "WHAT") == "SERVICE" else host_key)


def _mapped_values(
    context: Mapping[str, str],
    fields: Mapping[str, str],
    enabled: bool = True,
) -> Dict[str, str]:
    return {
        payload_name: _value(context, context_name) if enabled else ""
        for payload_name, context_name in fields.items()
    }


def _url_prefix(context: Mapping[str, str]) -> str:
    mode = _value(context, "PARAMETER_URL_PREFIX_1")
    if mode == "automatic_http":
        monitoring_host = _value(context, "MONITORING_HOST")
        site = _value(context, "OMD_SITE")
        if monitoring_host and site:
            return f"http://{monitoring_host}/{site}"
    elif mode == "automatic_https":
        monitoring_host = _value(context, "MONITORING_HOST")
        site = _value(context, "OMD_SITE")
        if monitoring_host and site:
            return f"https://{monitoring_host}/{site}"
    elif mode == "manual":
        configured = _value(context, "PARAMETER_URL_PREFIX_2").rstrip("/")
        parsed = parse.urlsplit(configured)
        path_segments = parsed.path.split("/")
        if "check_mk" in path_segments:
            check_mk_index = (
                len(path_segments) - 1 - path_segments[::-1].index("check_mk")
            )
            site_path = "/".join(path_segments[:check_mk_index])
            configured = parse.urlunsplit(
                (parsed.scheme, parsed.netloc, site_path, "", "")
            )
        return configured
    return ""


def _object_url(context: Mapping[str, str], context_key: str) -> str:
    prefix = _url_prefix(context)
    suffix = _value(context, context_key)
    if not prefix or not suffix:
        return ""
    if not suffix.startswith("/"):
        suffix = "/" + suffix
    return prefix.rstrip("/") + suffix


def build_payload(context: Mapping[str, str]) -> Dict[str, object]:
    """Build the stable xMatters payload for host and service notifications."""
    is_service = _value(context, "WHAT") == "SERVICE"

    payload: Dict[str, object] = {
        "source": "checkmk",
        "notification": {
            "type": _value(context, "NOTIFICATIONTYPE"),
            "object_type": "SERVICE" if is_service else "HOST",
            "timestamp_epoch_us": _value(context, "MICROTIME"),
            "datetime": _value(context, "LONGDATETIME"),
            "number": _selected_value(
                context, "HOSTNOTIFICATIONNUMBER", "SERVICENOTIFICATIONNUMBER"
            ),
            "author": _value(context, "NOTIFICATIONAUTHOR"),
            "author_name": _value(context, "NOTIFICATIONAUTHORNAME"),
            "author_alias": _value(context, "NOTIFICATIONAUTHORALIAS"),
            "comment": _value(context, "NOTIFICATIONCOMMENT"),
        },
        "checkmk": {
            "site": _value(context, "OMD_SITE"),
            "monitoring_host": _value(context, "MONITORING_HOST"),
            "host_url": _object_url(context, "HOSTURL"),
            "service_url": _object_url(context, "SERVICEURL") if is_service else "",
        },
        "host": {
            **_mapped_values(context, HOST_PAYLOAD_FIELDS),
            "tags": _value(context, "HOSTTAGS") or _value(context, "HOST_TAGS"),
        },
        "service": _mapped_values(context, SERVICE_PAYLOAD_FIELDS, enabled=is_service),
        "contact": _mapped_values(context, CONTACT_PAYLOAD_FIELDS),
    }
    return payload


def validate_trigger_url(raw_url: str) -> str:
    if not raw_url or not raw_url.strip():
        raise ConfigurationError(REQUIRED_TRIGGER_ERROR)
    try:
        parsed = parse.urlsplit(raw_url)
        if (
            parsed.scheme != "https"
            or not parsed.hostname
            or parsed.fragment
            or any(char.isspace() for char in raw_url)
        ):
            raise ValueError("unsupported URL")
        # Force validation of malformed bracketed hosts and ports.
        parsed.port
    except ValueError:
        raise ConfigurationError(INVALID_TRIGGER_ERROR) from None
    return raw_url


def _lookup_stored_password(password_id: str) -> str:
    """Resolve a Checkmk stored password behind one replaceable compatibility seam."""
    try:
        from cmk.utils import password_store  # type: ignore[import-not-found]
    except ImportError as exc:
        raise PasswordStoreError(
            f"{ERROR_PREFIX} Password store support is unavailable in this Checkmk version."
        ) from exc

    try:
        password = password_store.extract(password_id)
    except Exception as exc:
        raise PasswordStoreError(
            f"{ERROR_PREFIX} The configured password-store value could not be retrieved."
        ) from exc
    if password is None:
        raise PasswordStoreError(
            f"{ERROR_PREFIX} The configured password-store value could not be retrieved."
        )
    return str(password)


def _split_legacy_password(value: str) -> Tuple[str, str]:
    parts = value.split("\t", 1)
    if len(parts) == 1:
        parts = value.split(None, 1)
    if len(parts) == 1:
        return "explicit", parts[0]
    kind, secret_or_id = parts
    return kind, secret_or_id


def resolve_password(context: Mapping[str, str]) -> Optional[str]:
    """Resolve explicit and stored Password FormSpec encodings across Checkmk releases."""
    kind = _value(context, "PARAMETER_PASSWORD_2")
    if kind == "explicit_password":
        return _value(context, "PARAMETER_PASSWORD_3_2")
    if kind == "stored_password":
        password_id = _value(context, "PARAMETER_PASSWORD_3_1")
        if not password_id:
            raise PasswordStoreError(
                f"{ERROR_PREFIX} The configured password-store value is invalid."
            )
        return _lookup_stored_password(password_id)

    legacy_kind = _value(context, "PARAMETER_PASSWORD_1")
    legacy_value = _value(context, "PARAMETER_PASSWORD_2")
    if legacy_kind in ("store", "stored_password"):
        if not legacy_value:
            raise PasswordStoreError(
                f"{ERROR_PREFIX} The configured password-store value is invalid."
            )
        return _lookup_stored_password(legacy_value)
    if legacy_kind in ("password", "explicit_password"):
        return legacy_value

    combined = _value(context, "PARAMETER_PASSWORD")
    if combined:
        legacy_kind, legacy_value = _split_legacy_password(combined)
        if legacy_kind in ("store", "stored_password"):
            return _lookup_stored_password(legacy_value)
        if legacy_kind in ("password", "explicit_password"):
            return legacy_value
        return combined
    return None


def _basic_auth(context: Mapping[str, str]) -> Tuple[Optional[str], Optional[str]]:
    """Return the resolved password and header only when both credentials exist."""
    username = _value(context, "PARAMETER_USERNAME")
    if not username:
        return None, None
    password = resolve_password(context)
    if not password:
        return None, None
    return password, _encode_basic_auth(username, password)


def _encode_basic_auth(username: str, password: str) -> str:
    token = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
    return "Basic " + token


def _proxy_handler(proxy_setting: str) -> request.ProxyHandler:
    if not proxy_setting or proxy_setting == "NO_PROXY":
        return request.ProxyHandler({})
    if proxy_setting == "FROM_ENVIRONMENT":
        return request.ProxyHandler()
    try:
        parsed = parse.urlsplit(proxy_setting)
        if (
            parsed.scheme not in ("http", "https")
            or not parsed.hostname
            or parsed.fragment
            or any(char.isspace() for char in proxy_setting)
        ):
            raise ValueError("unsupported proxy URL")
        parsed.port
    except ValueError:
        raise ConfigurationError(
            f"{ERROR_PREFIX} Proxy configuration is invalid."
        ) from None
    return request.ProxyHandler({"http": proxy_setting, "https": proxy_setting})


def _tls_context(ignore_ssl: bool) -> ssl.SSLContext:
    context = ssl.create_default_context()
    if ignore_ssl:
        # This deliberately implements the ticket's explicit insecure TLS option.
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    return context


def post_notification(
    trigger_url: str,
    payload: Mapping[str, object],
    auth_header: Optional[str],
    proxy_setting: str,
    ignore_ssl: bool,
    timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
) -> HttpResult:
    body = json.dumps(
        payload,
        ensure_ascii=False,
        separators=(",", ":"),
        sort_keys=True,
    ).encode("utf-8")
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "User-Agent": USER_AGENT,
    }
    if auth_header:
        headers["Authorization"] = auth_header

    opener = request.build_opener(
        _proxy_handler(proxy_setting),
        request.HTTPSHandler(context=_tls_context(ignore_ssl)),
        NoRedirectHandler(),
    )
    req = request.Request(trigger_url, data=body, headers=headers, method="POST")

    try:
        with opener.open(req, timeout=timeout_seconds) as response:
            return HttpResult(
                status_code=int(response.status),
                body=response.read(MAX_RESPONSE_BYTES + 1),
            )
    except error.HTTPError as exc:
        return HttpResult(
            status_code=int(exc.code),
            body=exc.read(MAX_RESPONSE_BYTES + 1),
        )


def _secret_candidates(
    trigger_url: str,
    context: Mapping[str, str],
    password: Optional[str],
    auth_header: Optional[str],
) -> Sequence[str]:
    candidates = {
        trigger_url,
        password or "",
        auth_header or "",
        _value(context, "PARAMETER_USERNAME"),
        _value(context, "PARAMETER_PASSWORD_3_1"),
        _value(context, "PARAMETER_PASSWORD"),
        _value(context, "PARAMETER_PROXY_URL"),
    }
    for candidate_url in (
        trigger_url,
        _value(context, "PARAMETER_PROXY_URL"),
    ):
        try:
            parsed = parse.urlsplit(candidate_url)
        except ValueError:
            continue
        candidates.update(
            filter(
                None,
                (
                    parsed.username,
                    parsed.password,
                    *(value for _, value in parse.parse_qsl(parsed.query)),
                ),
            )
        )
        final_segment = parsed.path.rstrip("/").rsplit("/", 1)[-1]
        if len(final_segment) >= 8:
            candidates.add(final_segment)

    encoded_candidates = {
        encoded
        for candidate in candidates
        if candidate
        for encoded in (
            parse.quote(candidate, safe=""),
            parse.quote_plus(candidate, safe=""),
        )
    }
    candidates.update(encoded_candidates)
    return sorted(
        (candidate for candidate in candidates if candidate),
        key=len,
        reverse=True,
    )


def sanitize_text(text: str, secrets: Iterable[str]) -> str:
    result = text
    for secret in secrets:
        result = result.replace(secret, "[REDACTED]")
    result = " ".join(result.splitlines())
    result = re.sub(r"[\x00-\x1f\x7f]", " ", result)
    result = re.sub(r"\s+", " ", result).strip()
    return result


def _response_text(body: bytes, secrets: Iterable[str]) -> str:
    truncated = len(body) > MAX_RESPONSE_BYTES
    text = body[:MAX_RESPONSE_BYTES].decode("utf-8", errors="replace")
    text = sanitize_text(text, secrets)
    if truncated:
        text = f"{text} [response truncated]".strip()
    return text or "(empty response)"


def classify_result(result: HttpResult, secrets: Iterable[str]) -> Tuple[int, str]:
    status = result.status_code
    if 200 <= status <= 299:
        return EXIT_SUCCESS, f"Checkmk notification sent successfully. Status code [{status}]."
    if status in TEMPORARY_HTTP_STATUS_CODES or 500 <= status <= 599:
        return EXIT_TEMPORARY, TEMPORARY_ERROR
    response_text = _response_text(result.body, secrets)
    return (
        EXIT_FINAL,
        f"{ERROR_PREFIX} Flow Designer returned status code [{status}] "
        f"with the following: {response_text}.",
    )


def _temporary_exception(exc: BaseException) -> bool:
    reason = getattr(exc, "reason", None)
    if isinstance(exc, ssl.SSLCertVerificationError) or isinstance(
        reason, ssl.SSLCertVerificationError
    ):
        return False
    if isinstance(
        exc,
        (
            error.URLError,
            http.client.HTTPException,
            TimeoutError,
            socket.timeout,
            ConnectionError,
            ssl.SSLError,
        ),
    ):
        return True
    return isinstance(reason, (OSError, ssl.SSLError))


def run(
    environment: Optional[Mapping[str, str]] = None,
    timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
) -> int:
    context = collect_context(environment)
    trigger_url = _value(context, "PARAMETER_TRIGGER_URL")
    password: Optional[str] = None
    secrets: Sequence[str] = ()
    try:
        trigger_url = validate_trigger_url(trigger_url)
        password, auth_header = _basic_auth(context)
        secrets = _secret_candidates(trigger_url, context, password, auth_header)
        result = post_notification(
            trigger_url=trigger_url,
            payload=build_payload(context),
            auth_header=auth_header,
            proxy_setting=_value(context, "PARAMETER_PROXY_URL"),
            ignore_ssl="PARAMETER_IGNORE_SSL" in context,
            timeout_seconds=timeout_seconds,
        )
        exit_code, message = classify_result(result, secrets)
    except ConfigurationError as exc:
        exit_code = EXIT_FINAL
        message = sanitize_text(str(exc), secrets)
    except Exception as exc:
        if _temporary_exception(exc):
            exit_code = EXIT_TEMPORARY
            message = TEMPORARY_ERROR
        else:
            exit_code = EXIT_FINAL
            message = (
                f"{ERROR_PREFIX} The following error was encountered: "
                f"{sanitize_text(str(exc), secrets)}."
            )

    print(message)
    return exit_code


def main() -> int:
    return run()


if __name__ == "__main__":
    sys.exit(main())
