import Anthropic from '@anthropic-ai/sdk'

export const useClaude = () => {
  const runtimeConfig = useRuntimeConfig()
  
  const client = new Anthropic({
    apiKey: runtimeConfig.public.anthropicApiKey,
    dangerouslyAllowBrowser: true
  })

  const sendMessage = async (message, conversation = []) => {
    try {
      const messages = [
        ...conversation,
        { role: 'user', content: message }
      ]

      const response = await client.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1000,
        messages: messages
      })

      return {
        success: true,
        content: response.content[0].text,
        usage: response.usage
      }
    } catch (error) {
      console.error('Claude API Error:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  const sendStreamMessage = async (message, conversation = [], onChunk) => {
    try {
      const messages = [
        ...conversation,
        { role: 'user', content: message }
      ]

      const stream = await client.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1000,
        messages: messages,
        stream: true
      })

      let fullResponse = ''
      
      for await (const chunk of stream) {
        if (chunk.type === 'content_block_delta') {
          const text = chunk.delta.text
          fullResponse += text
          if (onChunk) {
            onChunk(text, fullResponse)
          }
        }
      }

      return {
        success: true,
        content: fullResponse
      }
    } catch (error) {
      console.error('Claude Stream API Error:', error)
      return {
        success: false,
        error: error.message
      }
    }
  }

  return {
    sendMessage,
    sendStreamMessage
  }
}