import { NextResponse } from 'next/server';
import { getCloseBotClient } from '@/lib/closebot';

export const dynamic = 'force-dynamic';

const COLORS = ['#22c55e', '#3b82f6', '#f97316', '#eab308', '#ef4444', '#a855f7', '#06b6d4', '#ec4899'];

interface LeaderboardEntry {
  botId?: string;
  botName?: string;
  name?: string;
  responses?: number;
  conversations?: number;
  messages?: number;
}

export async function GET() {
  const cb = getCloseBotClient();

  if (cb.isConfigured) {
    try {
      // Use leaderboard API for bot conversation counts
      const leaderboard = (await cb.getLeaderboard('responses', 10)) as LeaderboardEntry[];

      if (Array.isArray(leaderboard) && leaderboard.length > 0) {
        const bots = leaderboard.map((entry, i) => ({
          name: entry.botName || entry.name || `Bot ${i + 1}`,
          conversations: entry.responses ?? entry.conversations ?? entry.messages ?? 0,
          color: COLORS[i % COLORS.length],
        }));

        return NextResponse.json({ bots });
      }

      // If leaderboard returned empty, try getting bots list instead
      const rawBots = await cb.listBots();
      if (rawBots && rawBots.length > 0) {
        const bots = rawBots.slice(0, 8).map((b, i) => ({
          name: b.name,
          conversations: b.sources?.length ?? 0,
          color: COLORS[i % COLORS.length],
        }));
        return NextResponse.json({ bots });
      }
    } catch (error) {
      console.error('[analytics/bots] CloseBot API error:', error);
    }
  }

  // Return empty array if API unavailable
  return NextResponse.json({ bots: [] });
}
