#!/usr/bin/env python3
"""AlertOps Notification Plugin for Checkmk.

Sends host and service notifications from Checkmk to AlertOps
via webhook (JSON over HTTPS). Follows the same architecture as
the built-in PagerDuty and iLert plugins.

This is the entry point script. Checkmk invokes it directly and passes
notification context via NOTIFY_* environment variables. GUI-configured
parameters arrive as NOTIFY_PARAMETER_* variables.
"""

import sys
from datetime import datetime, timezone
from typing import Any

from cmk.notification_plugins.utils import (
    collect_context,
    host_url_from_context,
    post_request,
    process_by_status_code,
    service_url_from_context,
)


def alertops_severity(state: str) -> str:
    """Map Checkmk states to AlertOps severity levels."""
    return {
        "CRITICAL": "critical",
        "DOWN": "critical",
        "WARNING": "warning",
        "OK": "ok",
        "UP": "ok",
        "UNKNOWN": "unknown",
        "UNREACHABLE": "warning",
    }.get(state, "unknown")


def alertops_event_type(notification_type: str) -> str:
    """Map Checkmk notification types to AlertOps event types."""
    return {
        "PROBLEM": "PROBLEM",
        "RECOVERY": "RECOVERY",
        "ACKNOWLEDGEMENT": "ACKNOWLEDGEMENT",
        "CUSTOM": "CUSTOM",
        "FLAPPINGSTART": "PROBLEM",
        "FLAPPINGSTOP": "RECOVERY",
        "FLAPPINGDISABLED": "RECOVERY",
        "DOWNTIMESTART": "DOWNTIME_START",
        "DOWNTIMEEND": "DOWNTIME_END",
        "DOWNTIMECANCELLED": "DOWNTIME_CANCELLED",
    }.get(notification_type, notification_type)


def _alertops_msg(context: dict[str, str]) -> dict[str, Any]:
    """Build the AlertOps incident payload from Checkmk notification context."""
    notification_type = context.get("NOTIFICATIONTYPE", "")

    if context.get("WHAT") == "SERVICE":
        state = context["SERVICESTATE"]
        service_desc = context["SERVICEDESC"]
        event_key = "{HOSTNAME}_{SERVICEDESC}".format(**context).replace(" ", "_")
        summary = "{SERVICESTATE}: {SERVICEDESC} on {HOSTNAME}".format(**context)
        output = context.get("SERVICEOUTPUT", "")
        long_output = context.get("LONGSERVICEOUTPUT", "")
        detail_url = service_url_from_context(context)
    else:
        state = context["HOSTSTATE"]
        service_desc = ""
        event_key = context["HOSTNAME"]
        summary = "{HOSTNAME} is {HOSTSTATE}".format(**context)
        output = context.get("HOSTOUTPUT", "")
        long_output = context.get("LONGHOSTOUTPUT", "")
        detail_url = host_url_from_context(context)

    is_resolved = notification_type == "RECOVERY" or state in ("OK", "UP")
    timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

    payload: dict[str, Any] = {
        "EventKey": event_key,
        "Source": "Checkmk",
        "Host": context.get("HOSTNAME", ""),
        "HostAddress": context.get("HOSTADDRESS", ""),
        "Service": service_desc,
        "State": state,
        "Severity": alertops_severity(state),
        "NotificationType": alertops_event_type(notification_type),
        "Summary": summary,
        "Message": output,
        "Resolved": is_resolved,
        "Timestamp": timestamp,
    }

    if detail_url:
        payload["DetailsURL"] = detail_url

    # Unset macros arrive unexpanded (e.g. "$LONGHOSTOUTPUT$"); don't forward those.
    if long_output and not (long_output.startswith("$") and long_output.endswith("$")):
        payload["LongMessage"] = long_output

    return payload


def main() -> int:
    context = collect_context()

    # Webhook URL comes from GUI parameter (PARAMETER_ALERTOPS_WEBHOOK_URL)
    webhook_url = context.get("PARAMETER_ALERTOPS_WEBHOOK_URL", "")

    if not webhook_url:
        sys.stderr.write("No AlertOps webhook URL configured.\n")
        sys.stderr.write("Configure it in Setup → Notifications → Notification Rules.\n")
        return 2

    return process_by_status_code(
        post_request(_alertops_msg, url=webhook_url),
        success_code=200,
    )


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