#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage: notify_telegram.sh [YYYY-MM-DD]

Required env:
  TELEGRAM_BOT_TOKEN
  TELEGRAM_CHAT_ID
  PUBLIC_BASE_URL

Optional env:
  TELEGRAM_API_BASE   Default: https://api.telegram.org
  CURL_BIN            Default: curl
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DATE_ISO="${1:-$(date +%F)}"

: "${TELEGRAM_BOT_TOKEN:?missing env TELEGRAM_BOT_TOKEN}"
: "${TELEGRAM_CHAT_ID:?missing env TELEGRAM_CHAT_ID}"
: "${PUBLIC_BASE_URL:?missing env PUBLIC_BASE_URL (e.g. https://yourdomain.com/twitter-digest)}"

TELEGRAM_API_BASE="${TELEGRAM_API_BASE:-https://api.telegram.org}"
CURL_BIN="${CURL_BIN:-curl}"

if ! command -v "${CURL_BIN}" >/dev/null 2>&1 && [[ ! -x "${CURL_BIN}" ]]; then
  echo "[telegram] ERROR: curl binary not found/executable: ${CURL_BIN}"
  exit 2
fi

DAY_DIGEST="${ROOT}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/${DATE_ISO}"
DAY_TWEETS="${ROOT}/PHASES/PHASE-01-INGEST/tweets/archive/${DATE_ISO}"

DIGEST_JSON="${DAY_DIGEST}/digest.json"
INDEX_PHP="${DAY_DIGEST}/index.php"
IMAGES_OK="${DAY_TWEETS}/images_done.ok"

if [[ ! -f "${DIGEST_JSON}" ]]; then
  echo "[telegram] ERROR: missing ${DIGEST_JSON}"
  exit 2
fi
if [[ ! -f "${INDEX_PHP}" ]]; then
  echo "[telegram] ERROR: missing ${INDEX_PHP}"
  exit 2
fi
if [[ ! -f "${IMAGES_OK}" ]]; then
  echo "[telegram] ERROR: missing ${IMAGES_OK}"
  exit 2
fi

python3 - <<PY
import json
from pathlib import Path
p = Path(${DIGEST_JSON@Q})
json.loads(p.read_text(encoding="utf-8"))
PY

BASE="${PUBLIC_BASE_URL%/}"
URL="${BASE}/PHASES/PHASE-05-ORCHESTRATOR/digests/archive/${DATE_ISO}/"
API_URL="${TELEGRAM_API_BASE%/}/bot${TELEGRAM_BOT_TOKEN}/sendMessage"
TEXT="<b>Twitter digest ready</b>\n\nDate: ${DATE_ISO}\nURL: ${URL}"

if command -v "${CURL_BIN}" >/dev/null 2>&1; then
  CURL_CMD="${CURL_BIN}"
else
  CURL_CMD="${CURL_BIN}"
fi

response="$("${CURL_CMD}" -sS --fail -X POST "${API_URL}" \
  --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \
  --data-urlencode "parse_mode=HTML" \
  --data-urlencode "text=${TEXT}")"

if command -v jq >/dev/null 2>&1; then
  ok="$(printf '%s' "${response}" | jq -r '.ok // false')"
  if [[ "${ok}" != "true" ]]; then
    echo "[telegram] ERROR: API did not return ok=true"
    printf '%s\n' "${response}"
    exit 2
  fi
else
  if ! printf '%s' "${response}" | rg -q --smart-case '"ok"\s*:\s*true'; then
    echo "[telegram] ERROR: API response missing ok=true"
    printf '%s\n' "${response}"
    exit 2
  fi
fi

echo "[telegram] sent date=${DATE_ISO} url=${URL}"
