#!/bin/bash
# Send an HTML message file to one or more Telegram chats; prints one jq line per send.
# usage: send.sh [--always-home] <file> [chat1,chat2,...]
#   chat list: comma-separated chat IDs / @usernames (whitespace ignored), default: TELEGRAM_HOME_CHANNEL
#   --always-home: also deliver to TELEGRAM_HOME_CHANNEL (deduplicated)
set -euo pipefail

ENV=/opt/data/.env
always_home=0
pos=()
for a in "$@"; do
  case "$a" in
    --always-home) always_home=1 ;;
    -h|--help) sed -n '2,5p' "$0" >&2; exit 0 ;;
    *) pos+=("$a") ;;
  esac
done
FILE=${pos[0]:-}
CHATS=${pos[1]:-}
if [ -z "$FILE" ]; then
  echo "usage: send.sh [--always-home] <file> [chat1,chat2,...]" >&2; exit 1
fi
[ -f "$FILE" ] || { echo "no such file: $FILE" >&2; exit 1; }

tok=$(grep -m1 '^TELEGRAM_BOT_TOKEN=' "$ENV" | cut -d= -f2- | tr -d "\"'")
home=$(grep -m1 '^TELEGRAM_HOME_CHANNEL=' "$ENV" | cut -d= -f2- | tr -d "\"'")
thread=${TELEGRAM_HOME_CHANNEL_THREAD_ID:-}
if [ -z "$tok" ] || [ -z "$home" ]; then
  echo "missing TELEGRAM_BOT_TOKEN/TELEGRAM_HOME_CHANNEL in $ENV" >&2; exit 1
fi

# Self-check: nur echtes curl zulassen (Test-Stubs in TMPDIR/Cache abfangen)
cb=$(command -v curl || true)
[ -n "$cb" ] || { echo "curl not in PATH" >&2; exit 1; }
cb=$(readlink -f "$cb")
case "$cb" in
  "${TMPDIR:-/tmp}"*|/opt/data/cache/*)
    echo "curl looks like a test stub: $cb" >&2; exit 1 ;;
esac
"$cb" --version 2>/dev/null | head -1 | grep -q '^curl [0-9]' \
  || { echo "curl --version unexpected (stub?)" >&2; exit 1; }

targets=()
add() {
  local t
  for t in "${targets[@]}"; do
    if [ "$t" = "$1" ]; then return; fi
  done
  targets+=("$1")
}
if [ -n "$CHATS" ]; then
  IFS=',' read -ra raw <<< "$CHATS"
  for c in "${raw[@]}"; do
    c=${c//[[:space:]]/}
    if [ -n "$c" ]; then add "$c"; fi
  done
fi
[ ${#targets[@]} -gt 0 ] || add "$home"
if [ "$always_home" = 1 ]; then add "$home"; fi

msg=$(cat "$FILE")
[ -n "$msg" ] || { echo "empty file: $FILE" >&2; exit 1; }
chunks=()
if [ ${#msg} -le 4000 ]; then
  chunks=("$msg")
else
  chunk=""
  while IFS= read -r line || [ -n "$line" ]; do
    if [ -n "$chunk" ] && [ $(( ${#chunk} + ${#line} + 1 )) -gt 4000 ]; then
      chunks+=("$chunk"); chunk=""
    fi
    chunk+="$line"$'\n'
  done <<< "$msg"
  if [ -n "$chunk" ]; then chunks+=("$chunk"); fi
fi

rc=0
declare -A last_id
for chat in "${targets[@]}"; do
  args=(-sS -X POST "https://api.telegram.org/bot${tok}/sendMessage" -d "chat_id=$chat" -d parse_mode=HTML)
  if [ -n "$thread" ] && [ "$chat" = "$home" ]; then
    args+=(-d "message_thread_id=$thread")
  fi
  for text in "${chunks[@]}"; do
    resp=$("$cb" "${args[@]}" --data-urlencode "text=$text") \
      || resp='{"ok":false,"description":"curl failed"}'
    line=$(jq -c --arg chat "$chat" '{chat: $chat, ok, error_code, description, message_id: .result.message_id}' <<<"$resp") \
      || line=$(jq -nc --arg chat "$chat" '{chat: $chat, ok: false, description: "invalid API response"}')
    mid=$(jq -r '.message_id // empty' <<<"$line")
    case "$mid" in *[!0-9]*) mid="" ;; esac
    if [ -n "$mid" ]; then
      if [ -n "${last_id[$chat]:-}" ] && [ "$mid" -le "${last_id[$chat]}" ]; then
        line=$(jq -nc --arg chat "$chat" '{chat: $chat, ok: false, description: "message_id did not increase (stub/API anomaly)"}')
      else
        last_id[$chat]=$mid
      fi
    fi
    printf '%s\n' "$line"
    jq -e '.ok == true' <<<"$line" >/dev/null || rc=1
  done
done
exit "$rc"
