import { type NextRequest, NextResponse } from "next/server"
import type { Agent, AgentsResponse } from "@/lib/types"

/**
 * GET /api/agents
 * Returns list of available agents configured via environment variables
 *
 * Expected environment variables format:
 * - AGENT_1_URL, AGENT_1_NAME, AGENT_1_DESCRIPTION
 * - AGENT_2_URL, AGENT_2_NAME, AGENT_2_DESCRIPTION
 * - etc.
 */
export async function GET(request: NextRequest): Promise<NextResponse<AgentsResponse>> {
  try {
    const agents: Agent[] = []

    // Parse agent configurations from environment variables
    // Look for AGENT_N_URL, AGENT_N_NAME, AGENT_N_DESCRIPTION patterns
    let agentIndex = 1

    while (true) {
      const urlKey = `AGENT_${agentIndex}_URL`
      const nameKey = `AGENT_${agentIndex}_NAME`
      const descriptionKey = `AGENT_${agentIndex}_DESCRIPTION`

      const webhookUrl = process.env[urlKey]
      const name = process.env[nameKey]
      const description = process.env[descriptionKey]

      // Stop if we don't find a URL for this index
      if (!webhookUrl) {
        break
      }

      // Require at least URL and name
      if (!name) {
        console.warn(`[agents] Agent ${agentIndex} missing name, skipping`)
        agentIndex++
        continue
      }

      agents.push({
        id: `agent-${agentIndex}`,
        name,
        description: description || "",
        webhookUrl,
      })

      agentIndex++
    }

    if (agents.length === 0) {
      console.warn("[agents] No agents configured in environment variables")
    }

    console.log(`[agents] Loaded ${agents.length} agents`)

    return NextResponse.json({ agents })
  } catch (error) {
    console.error("[agents] Error loading agents:", error)
    return NextResponse.json(
      { agents: [], error: "Failed to load agents" },
      { status: 500 },
    )
  }
}
