#!/usr/bin/env bash
# ===============================================================================================================
# telegram-pipeline-notify.sh - Notificaciones enriquecidas de Telegram para pipelines de Bitbucket
# Descripcion:
#       Envía alertas detalladas a Telegram incluyendo branch, commit, build number,
#       autor y estado del despliegue. Requiere TELEGRAM_BOT_TOKEN y TELEGRAM_CHAT_ID.
#
# Uso:
#       bash scripts/telegram-pipeline-notify.sh <start|success|failure> [mensaje_extra]
#
# Autor: Area de Tecnologia y Desarrollo - CCsoft
# ===============================================================================================================

set -euo pipefail

NOTIFY_TYPE="${1:-}"
EXTRA_MESSAGE="${2:-}"

TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN:-${DEV_TELEGRAM_BOT_TOKEN:-${PROD_TELEGRAM_BOT_TOKEN:-}}}"
TELEGRAM_CHAT_ID="${TELEGRAM_CHAT_ID:-${DEV_TELEGRAM_CHAT_ID:-${PROD_TELEGRAM_CHAT_ID:-}}}"

if [[ -z "$TELEGRAM_BOT_TOKEN" ]]; then
    echo "[WARN] TELEGRAM_BOT_TOKEN no definido. Saltando notificacion." >&2
    exit 0
fi

if [[ -z "$TELEGRAM_CHAT_ID" ]]; then
    echo "[WARN] TELEGRAM_CHAT_ID no definido. Saltando notificacion." >&2
    exit 0
fi

if [[ -z "$NOTIFY_TYPE" ]]; then
    echo "[ERROR] Debe proporcionar el tipo de notificacion: start, success o failure" >&2
    exit 1
fi

# Escapa caracteres reservados en MarkdownV2: _ * [ ] ( ) ~ ` > # + - = | { } . !
telegram_escape() {
    printf '%s' "$1" | python3 -c 'import re, sys; text = sys.stdin.read(); print(re.sub(r"([_*\[\]()~`>#+=|{}.!-])", r"\\\1", text), end="")'
}

# -------------------------------------------------------------------------------
# Variables de contexto del pipeline
# -------------------------------------------------------------------------------
BRANCH="${BITBUCKET_BRANCH:-unknown}"
COMMIT="${BITBUCKET_COMMIT:-unknown}"
BUILD_NUMBER="${BITBUCKET_BUILD_NUMBER:-unknown}"
REPO="${BITBUCKET_REPO_SLUG:-proyectosacc}"
WORKSPACE="${BITBUCKET_WORKSPACE:-ccsoft1}"
AUTHOR="${BITBUCKET_STEP_TRIGGERER_UUID:-desconocido}"

# Truncar commit a 7 caracteres si es largo
if [[ "${#COMMIT}" -gt 7 ]]; then
    COMMIT_SHORT="${COMMIT:0:7}"
else
    COMMIT_SHORT="$COMMIT"
fi

# Timestamp actual
TIMESTAMP="$(date '+%Y-%m-%d %H:%M:%S %Z')"

# Escapar variables dinamicas para MarkdownV2
BRANCH_ESC="$(telegram_escape "$BRANCH")"
COMMIT_ESC="$(telegram_escape "$COMMIT_SHORT")"
BUILD_ESC="$(telegram_escape "$BUILD_NUMBER")"
REPO_ESC="$(telegram_escape "$REPO")"
AUTHOR_ESC="$(telegram_escape "$AUTHOR")"
TIMESTAMP_ESC="$(telegram_escape "$TIMESTAMP")"
EXTRA_ESC="$(telegram_escape "$EXTRA_MESSAGE")"

# -------------------------------------------------------------------------------
# Armar mensaje segun tipo
# -------------------------------------------------------------------------------
case "$NOTIFY_TYPE" in
    start)
        EMOJI="🚀"
        STATUS="INICIANDO"
        ;;
    success)
        EMOJI="✅"
        STATUS="COMPLETADO EXITOSAMENTE"
        ;;
    failure)
        EMOJI="❌"
        STATUS="FALLÓ"
        ;;
    *)
        EMOJI="ℹ️"
        STATUS="$NOTIFY_TYPE"
        ;;
esac

STATUS_ESC="$(telegram_escape "$STATUS")"

MESSAGE="${EMOJI} Pipeline *${REPO_ESC}* *${STATUS_ESC}*

*Branch:* \`${BRANCH_ESC}\`
*Commit:* \`${COMMIT_ESC}\`
*Build:* \#${BUILD_ESC}
*Autor:* ${AUTHOR_ESC}
*Hora:* ${TIMESTAMP_ESC}"

if [[ -n "$EXTRA_MESSAGE" ]]; then
    MESSAGE="${MESSAGE}
*Detalle:* ${EXTRA_ESC}"
fi

# -------------------------------------------------------------------------------
# Enviar mensaje
# -------------------------------------------------------------------------------
RESPONSE=$(curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
    -d "chat_id=${TELEGRAM_CHAT_ID}" \
    --data-urlencode "text=${MESSAGE}" \
    -d "parse_mode=MarkdownV2")

if echo "$RESPONSE" | grep -q '"ok":true'; then
    echo "[INFO] Notificacion enviada a Telegram"
else
    echo "[WARN] Error enviando notificacion: $RESPONSE" >&2
    exit 0
fi
