// bot/src/providers/llm/anthropic.ts — Anthropic Claude provider

import Anthropic from '@anthropic-ai/sdk'
import type { LLMConfig } from '../../types.js'
import type { LLMProvider } from './index.js'

const TITLE_MODEL = 'claude-haiku-4-5'
const TIMEOUT_MS = 10_000

export class AnthropicProvider implements LLMProvider {
  private client: Anthropic

  constructor(private config: LLMConfig) {
    this.client = new Anthropic({
      apiKey: config.api_key,
      timeout: TIMEOUT_MS,
    })
  }

  async generateTitle(description: string): Promise<string> {
    const message = await this.client.messages.create({
      model: TITLE_MODEL,
      max_tokens: 64,
      messages: [
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text: `Generate a concise card title (maximum 80 characters) for the following feature description. Return ONLY the title text, no quotes, no explanation.\n\nFeature description:\n${description}`,
            },
          ],
        },
      ],
    })

    const block = message.content[0]
    if (block.type !== 'text') {
      throw new Error('Anthropic returned unexpected content type for generateTitle')
    }

    return block.text.trim().slice(0, 80)
  }

  async mergeContext(previous: string, newText: string): Promise<string> {
    const message = await this.client.messages.create({
      model: this.config.model,
      max_tokens: 1024,
      messages: [
        {
          role: 'user',
          content: [
            {
              type: 'text',
              text: `You are a context consolidation assistant. Merge the previous context and the new text into a single, coherent, and concise summary that preserves all important information. Return ONLY the merged context, no preamble.\n\nPrevious context:\n${previous}\n\nNew text:\n${newText}`,
            },
          ],
        },
      ],
    })

    const block = message.content[0]
    if (block.type !== 'text') {
      throw new Error('Anthropic returned unexpected content type for mergeContext')
    }

    return block.text.trim()
  }

  async generateArtifact(systemPrompt: string, userInput: string): Promise<string> {
    // Geração elaborada (ex.: ideia rica) — usa o prompt do subagent como system,
    // o modelo configurado e um timeout maior que o padrão de título/merge.
    const message = await this.client.messages.create(
      {
        model: this.config.model,
        max_tokens: 4096,
        system: systemPrompt,
        messages: [{ role: 'user', content: userInput }],
      },
      { timeout: 120_000 },
    )

    return message.content
      .filter((block): block is Anthropic.TextBlock => block.type === 'text')
      .map((block) => block.text)
      .join('\n')
      .trim()
  }
}
