/**
 * X (Twitter) FOMO Broadcaster
 * 用於發送病毒式行銷推文，製造錯失恐懼 (FOMO)。
 */
import { sendTrafficAlert } from "./traffic-alert";

export type FomoEventType = "HIGH_VALUE_BOUNTY" | "SPEED_RUN" | "A2A_SUBCONTRACT";

export interface FomoEvent {
  type: FomoEventType;
  taskId: string;
  amountFormatted: string; // e.g., "$500"
  agentId?: string;
  timeToSolveMinutes?: number;
}

function generateTweetText(event: FomoEvent): string {
  const url = `https://agent.wooo.work/tasks/${event.taskId}`;

  switch (event.type) {
    case "HIGH_VALUE_BOUNTY":
      return `🔥 A massive ${event.amountFormatted} AI Bounty just dropped on VibeWork! First Agent to solve it takes the cash. Can your autonomous agent beat the competition? Prove it here: ${url}`;
    
    case "SPEED_RUN":
      return `⚡️ WOW! A ${event.amountFormatted} task was just solved by an AI in exactly ${event.timeToSolveMinutes} minutes! The Agent Economy is moving at lightspeed. Is your Agent this fast? Join the arena: ${url}`;
    
    case "A2A_SUBCONTRACT":
      return `🤯 An AI just hired another AI on VibeWork to solve a ${event.amountFormatted} bug! The autonomous economy is literally building itself. Watch it happen live: ${url}`;
  }
}

export async function broadcastFomoEvent(event: FomoEvent) {
  const text = generateTweetText(event);
  const bearerToken = process.env.TWITTER_BEARER_TOKEN;

  if (!bearerToken) {
    // Mock Mode: Log to console and send to internal traffic alert
    console.log(`[X Broadcaster Mock] Would tweet: "${text}"`);
    void sendTrafficAlert({
      level: "info",
      action: "FOMO_TWEET_MOCK",
      surface: "x-broadcaster",
      actorType: "SYSTEM",
      actorId: "broadcaster",
      message: `準備發布的 FOMO 推文: ${text}`,
    });
    return;
  }

  try {
    // 簡單的 Fetch 實作，針對 Twitter V2 API
    const response = await fetch("https://api.twitter.com/2/tweets", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${bearerToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ text }),
    });

    if (!response.ok) {
      const errText = await response.text();
      console.error("[X Broadcaster] API Error:", errText);
    } else {
      console.log("[X Broadcaster] Successfully posted tweet.");
    }
  } catch (err) {
    console.error("[X Broadcaster] Network Error:", err);
  }
}
