/**
 * alert.ts — operational alerts to Telegram (tiaBaby_Bot).
 *
 * Best-effort: every function swallows its own errors so a failed alert can
 * never cascade into another failure (mirrors logError / logAudit).
 *
 * Env:
 *   TELEGRAM_BOT_TOKEN  — from @BotFather
 *   TELEGRAM_CHAT_ID    — chat / channel / group id to post into
 *
 * Get your chat id: send any message to the bot, then
 *   curl "https://api.telegram.org/bot<TOKEN>/getUpdates"
 * and read result[].message.chat.id  (negative for groups/channels)
 */

export type AlertLevel = "info" | "warn" | "error" | "fatal";

const EMOJI: Record<AlertLevel, string> = {
  info: "🔵",
  warn: "🟡",
  error: "🔴",
  fatal: "🚨",
};

/** Escape the three characters Telegram HTML parse-mode treats specially. */
function escapeHtml(s: string): string {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function istNow(): string {
  return new Date().toLocaleString("en-IN", {
    timeZone: "Asia/Kolkata",
    day: "numeric",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
    hour12: true,
  });
}

export interface AlertOptions {
  /** Key/value rows rendered (bold key) beneath the message. */
  fields?: Record<string, string | number>;
  /** Send without a notification sound. */
  silent?: boolean;
}

/**
 * Send an operational alert to Telegram. Never throws.
 * @returns true if delivered, false if skipped or failed.
 */
export async function sendAlert(
  level: AlertLevel,
  title: string,
  detail?: string,
  opts: AlertOptions = {},
): Promise<boolean> {
  const token = process.env.TELEGRAM_BOT_TOKEN;
  const chatId = process.env.TELEGRAM_CHAT_ID;
  if (!token || !chatId) {
    console.warn("sendAlert: TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID not set — skipping");
    return false;
  }

  const lines: string[] = [`${EMOJI[level]} <b>${escapeHtml(title)}</b>`];
  if (detail) lines.push("", escapeHtml(detail.slice(0, 3500)));
  if (opts.fields && Object.keys(opts.fields).length) {
    lines.push("");
    for (const [k, v] of Object.entries(opts.fields)) {
      lines.push(`<b>${escapeHtml(k)}:</b> ${escapeHtml(String(v))}`);
    }
  }
  lines.push("", `<i>🌸 Tia · ${istNow()} IST</i>`);

  try {
    const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        chat_id: chatId,
        text: lines.join("\n"),
        parse_mode: "HTML",
        disable_web_page_preview: true,
        disable_notification: !!opts.silent,
      }),
    });
    if (!res.ok) {
      console.error("sendAlert: Telegram API error", res.status, await res.text().catch(() => ""));
      return false;
    }
    return true;
  } catch (e) {
    console.error("sendAlert failed:", e);
    return false;
  }
}
