/** Bot token: `{botId}:{secret}` — e.g. `123456789:AAH...` */
function looksLikeBotToken(value: string | undefined): boolean {
  return Boolean(value && /^\d+:[A-Za-z0-9_-]+$/.test(value.trim()))
}

/** Chat / group / channel id — numeric, often negative for groups */
function looksLikeChatId(value: string | undefined): boolean {
  return Boolean(value && /^-?\d+$/.test(value.trim()))
}

type TelegramConfig = {
  botToken: string
  chatId: string
  apiUrl: string
}

let cachedConfig: TelegramConfig | null | undefined

export function getTelegramConfig(): TelegramConfig | null {
  if (cachedConfig !== undefined) return cachedConfig

  let botToken = process.env.TELEGRAM_BOT_TOKEN?.trim()
  let chatId = process.env.TELEGRAM_CHAT_ID?.trim()

  if (!botToken || !chatId) {
    cachedConfig = null
    return null
  }

  // Common setup mistake: values pasted into the wrong variable
  if (looksLikeBotToken(chatId) && looksLikeChatId(botToken)) {
    console.warn(
      '[telegram] TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID appear swapped — using corrected values'
    )
    ;[botToken, chatId] = [chatId, botToken]
  } else if (!looksLikeBotToken(botToken)) {
    console.error(
      '[telegram] TELEGRAM_BOT_TOKEN must look like 123456789:AAH... (from @BotFather)'
    )
    cachedConfig = null
    return null
  } else if (!looksLikeChatId(chatId)) {
    console.error(
      '[telegram] TELEGRAM_CHAT_ID must be a numeric chat id (e.g. -1001234567890)'
    )
    cachedConfig = null
    return null
  }

  cachedConfig = {
    botToken,
    chatId,
    apiUrl: `https://api.telegram.org/bot${botToken}`,
  }
  return cachedConfig
}
