type BroadcastTask = {
  id: string;
  title: string;
  reward_amount: number;
  reward_currency: string;
  required_stack?: string[] | null;
};

const TELEGRAM_BOT_TOKEN = (process.env.TELEGRAM_BOT_TOKEN || "").trim();
const TELEGRAM_CHAT_ID = (
  process.env.A2A_TELEGRAM_CHAT_ID ||
  process.env.TELEGRAM_CHAT_ID ||
  ""
).trim();
const A2A_TELEGRAM_BROADCAST_ENABLED =
  process.env.A2A_TELEGRAM_BROADCAST_ENABLED?.trim().toLowerCase() === "true";
const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL || "https://agent.wooo.work").replace(/\/$/, "");

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function formatReward(task: BroadcastTask) {
  const amount = (task.reward_amount / 100).toFixed(2);
  return `${amount} ${task.reward_currency}`;
}

function buildTaskMessage(task: BroadcastTask) {
  const stack = task.required_stack?.length ? task.required_stack.join(", ") : "未指定";
  const taskUrl = `${SITE_URL}/tasks/${task.id}`;

  return (
    `<b>VibeWork A2A 任務廣播</b>` +
    `\n- 任務: <b>${escapeHtml(task.title)}</b>` +
    `\n- Reward: <code>${escapeHtml(formatReward(task))}</code>` +
    `\n- Stack: <code>${escapeHtml(stack)}</code>` +
    `\n- Task ID: <code>${escapeHtml(task.id)}</code>` +
    `\n- 入口: ${escapeHtml(taskUrl)}` +
    `\n\n外部 Agent 請先完成 Agent Card / wallet 綁定與白名單審核，再 claim 或 bid。`
  );
}

export async function broadcastViaTelegram(task: BroadcastTask) {
  if (!A2A_TELEGRAM_BROADCAST_ENABLED) {
    console.warn("[Telegram Broadcaster] A2A_TELEGRAM_BROADCAST_ENABLED is not true. Skipping broadcast.");
    return false;
  }

  if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
    console.warn("[Telegram Broadcaster] TELEGRAM_BOT_TOKEN or A2A_TELEGRAM_CHAT_ID/TELEGRAM_CHAT_ID is missing. Skipping broadcast.");
    return false;
  }

  const response = await fetch(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      chat_id: TELEGRAM_CHAT_ID,
      text: buildTaskMessage(task),
      parse_mode: "HTML",
      disable_web_page_preview: true,
    }),
  });

  if (!response.ok) {
    const body = await response.text();
    console.error(`[Telegram Broadcaster] Telegram API ${response.status}: ${body.slice(0, 200)}`);
    return false;
  }

  console.log(`[Telegram Broadcaster] Broadcasted Task ${task.id} to Telegram.`);
  return true;
}
