/**
 * Agent Definitions
 * 
 * Define your AI agents here. Each agent is a simple function that:
 * 1. Receives input
 * 2. Calls AI providers
 * 3. Returns output
 * 
 * To use AI providers, import aiProviderManager from '../ai-providers'
 */

import { aiProviderManager } from '../ai-providers/index.js'

export interface AgentExecutor {
  execute(input: any): Promise<any>
}

/**
 * Example Agent: Test Agent (No AI)
 */
export const testAgent: AgentExecutor = {
  async execute(input: any) {
    return {
      message: 'Hello from test agent!',
      input: input,
      timestamp: new Date().toISOString(),
      status: 'success'
    }
  }
}

/**
 * Example Agent: Echo Agent (No AI)
 */
export const echoAgent: AgentExecutor = {
  async execute(input: any) {
    return {
      echo: input,
      timestamp: new Date().toISOString()
    }
  }
}

/**
 * Example Agent: GPT-4 Assistant
 */
export const gpt4Assistant: AgentExecutor = {
  async execute(input: any) {
    const { prompt, systemPrompt, temperature, maxTokens } = input.data || {}
    
    if (!prompt) {
      throw new Error('prompt is required')
    }
    
    const messages: any[] = []
    
    if (systemPrompt) {
      messages.push({ role: 'system', content: systemPrompt })
    }
    
    messages.push({ role: 'user', content: prompt })
    
    const response = await aiProviderManager.complete({
      model: 'gpt-4',
      messages,
      temperature: temperature ?? 0.7,
      maxTokens: maxTokens ?? 1000
    })
    
    return {
      result: response.content,
      model: response.model,
      usage: response.usage,
      cost: await aiProviderManager.getProvider('openai')?.estimateCost({
        model: 'gpt-4',
        messages
      })
    }
  }
}

/**
 * Example Agent: Claude Assistant
 */
export const claudeAssistant: AgentExecutor = {
  async execute(input: any) {
    const { prompt, systemPrompt, temperature, maxTokens } = input.data || {}
    
    if (!prompt) {
      throw new Error('prompt is required')
    }
    
    const messages: any[] = []
    
    if (systemPrompt) {
      messages.push({ role: 'system', content: systemPrompt })
    }
    
    messages.push({ role: 'user', content: prompt })
    
    const response = await aiProviderManager.complete({
      model: 'claude-3-5-sonnet-20241022',
      messages,
      temperature: temperature ?? 0.7,
      maxTokens: maxTokens ?? 1000
    })
    
    return {
      result: response.content,
      model: response.model,
      usage: response.usage,
      cost: await aiProviderManager.getProvider('anthropic')?.estimateCost({
        model: 'claude-3-5-sonnet-20241022',
        messages
      })
    }
  }
}

/**
 * Example Agent: Sentiment Analyzer
 */
export const sentimentAnalyzer: AgentExecutor = {
  async execute(input: any) {
    const { texts } = input.data || {}
    
    if (!texts || !Array.isArray(texts)) {
      throw new Error('texts array is required')
    }
    
    const results: Array<{ text: string; sentiment: string; confidence: number }> = []
    
    for (const text of texts) {
      const response = await aiProviderManager.complete({
        model: 'gpt-3.5-turbo',
        messages: [
          { 
            role: 'system', 
            content: 'You are a sentiment analyzer. Respond with ONLY one word: positive, negative, or neutral.' 
          },
          { role: 'user', content: text }
        ],
        temperature: 0.3,
        maxTokens: 10
      })
      
      results.push({
        text,
        sentiment: response.content.toLowerCase().trim(),
        confidence: 0.95
      })
    }
    
    return {
      results,
      model: 'gpt-3.5-turbo',
      totalAnalyzed: texts.length
    }
  }
}

/**
 * Example Agent: Text Summarizer
 */
export const textSummarizer: AgentExecutor = {
  async execute(input: any) {
    const { text, maxLength } = input.data || {}
    
    if (!text) {
      throw new Error('text is required')
    }
    
    const response = await aiProviderManager.complete({
      model: 'gpt-4',
      messages: [
        { 
          role: 'system', 
          content: `Summarize the following text in ${maxLength || 100} words or less.` 
        },
        { role: 'user', content: text }
      ],
      temperature: 0.5,
      maxTokens: (maxLength || 100) * 2
    })
    
    return {
      original_length: text.length,
      summary: response.content,
      summary_length: response.content.length,
      compression_ratio: (response.content.length / text.length * 100).toFixed(2) + '%',
      usage: response.usage
    }
  }
}

/**
 * Example Agent: Multi-Step Researcher
 */
export const researchAgent: AgentExecutor = {
  async execute(input: any) {
    const { topic } = input.data || {}
    
    if (!topic) {
      throw new Error('topic is required')
    }
    
    // Step 1: Generate research questions
    const questionsResponse = await aiProviderManager.complete({
      model: 'gpt-4',
      messages: [
        { 
          role: 'system', 
          content: 'Generate 3 research questions about this topic. Return only the questions, one per line.' 
        },
        { role: 'user', content: topic }
      ],
      temperature: 0.7,
      maxTokens: 200
    })
    
    const questions = questionsResponse.content.split('\n').filter(q => q.trim())
    
    // Step 2: Answer each question
    const answers: Array<{ question: string; answer: string }> = []
    for (const question of questions) {
      const answerResponse = await aiProviderManager.complete({
        model: 'gpt-4',
        messages: [
          { role: 'system', content: 'Answer this research question concisely.' },
          { role: 'user', content: question }
        ],
        temperature: 0.7,
        maxTokens: 300
      })
      
      answers.push({
        question,
        answer: answerResponse.content
      })
    }
    
    // Step 3: Synthesize findings
    const synthesisResponse = await aiProviderManager.complete({
      model: 'gpt-4',
      messages: [
        { 
          role: 'system', 
          content: 'Synthesize these research findings into a cohesive summary.' 
        },
        { 
          role: 'user', 
          content: JSON.stringify(answers, null, 2) 
        }
      ],
      temperature: 0.7,
      maxTokens: 500
    })
    
    return {
      topic,
      questions,
      answers,
      synthesis: synthesisResponse.content,
      totalSteps: 3
    }
  }
}

/**
 * Agent Registry
 * 
 * Add your agents here so they can be called by agent_id
 */
export const agents: Record<string, AgentExecutor> = {
  'test-agent': testAgent,
  'echo-agent': echoAgent,
  'gpt4-assistant': gpt4Assistant,
  'claude-assistant': claudeAssistant,
  'sentiment-analyzer': sentimentAnalyzer,
  'text-summarizer': textSummarizer,
  'research-agent': researchAgent
}

/**
 * Get agent by ID
 */
export function getAgent(agentId: string): AgentExecutor | undefined {
  return agents[agentId]
}

/**
 * List all available agents
 */
export function listAgents(): string[] {
  return Object.keys(agents)
}

