// bot/src/providers/llm/openai.ts — OpenAI provider

import OpenAI from 'openai'
import type { LLMConfig } from '../../types.js'
import type { LLMProvider } from './index.js'

const TITLE_MODEL = 'gpt-4o-mini'
const TIMEOUT_MS = 10_000

export class OpenAIProvider implements LLMProvider {
  private client: OpenAI

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

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

    const text = completion.choices[0]?.message?.content
    if (!text) {
      throw new Error('OpenAI returned empty content for generateTitle')
    }

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

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

    const text = completion.choices[0]?.message?.content
    if (!text) {
      throw new Error('OpenAI returned empty content for mergeContext')
    }

    return text.trim()
  }

  async generateArtifact(systemPrompt: string, userInput: string): Promise<string> {
    const completion = await this.client.chat.completions.create(
      {
        model: this.config.model,
        max_tokens: 4096,
        messages: [
          { role: 'system', content: systemPrompt },
          { role: 'user', content: userInput },
        ],
      },
      { timeout: 120_000 },
    )

    const text = completion.choices[0]?.message?.content
    if (!text) {
      throw new Error('OpenAI returned empty content for generateArtifact')
    }
    return text.trim()
  }
}
