/**
 * Agent factory for loading and managing agent definitions
 * Handles both standard agents and custom agents
 */

import type { AgentDefinition } from '@/lib/types'
import type { PinnedAgent } from '@/lib/types'
import { getStandardAgent, STANDARD_AGENTS } from './definitions'

/**
 * Load an agent definition by ID
 * Supports both standard agents (agent-N) and custom agents (custom-{uuid})
 *
 * @param agentId - The agent ID to load
 * @param customAgentData - Optional custom agent data from request (for custom agents)
 * @returns The agent definition, or throws an error if not found
 */
export async function getAgentDefinition(
  agentId: string,
  customAgentData?: {
    systemPrompt: string
    tools?: AgentDefinition['tools']
  }
): Promise<AgentDefinition> {
  // Check if it's a standard agent
  const standardAgent = getStandardAgent(agentId)
  if (standardAgent) {
    return standardAgent
  }

  // Check if it's a custom agent
  if (agentId.startsWith('custom-')) {
    if (!customAgentData) {
      throw new Error(
        `Custom agent ${agentId} requires systemPrompt in request body`
      )
    }

    // Build a custom agent definition from the provided data
    const customAgent: AgentDefinition = {
      id: agentId,
      name: agentId, // Will be overridden by client-side data
      description: 'Custom agent',
      systemPrompt: customAgentData.systemPrompt,
      tools: customAgentData.tools,
      temperature: 0.7,
      maxTokens: 4096,
    }

    return customAgent
  }

  throw new Error(`Agent not found: ${agentId}`)
}

/**
 * Get all available standard agents for the client
 * Used by /api/agents endpoint
 */
export function getAllAvailableAgents(): Array<{
  id: string
  name: string
  description: string
}> {
  return Object.values(STANDARD_AGENTS).map((agent) => ({
    id: agent.id,
    name: agent.name,
    description: agent.description,
  }))
}

/**
 * Validate that an agent exists and is accessible
 */
export function agentExists(agentId: string): boolean {
  // Standard agents
  if (getStandardAgent(agentId)) {
    return true
  }

  // Custom agents exist server-side if they're created by the user
  // The validation happens when systemPrompt is provided
  if (agentId.startsWith('custom-')) {
    return true // Will be validated when loading
  }

  return false
}
