import { buildSystemPrompt } from '../utils/promptBuilder.js'

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:3001/api'

class DeepSeekAPI {
  constructor(config) {
    this.providerId = config.providerId
    this.model = config.model
    this.appId = config.appId || ''
    this.baseURL = `${API_BASE}/llm/stream`
    console.log('LLM 代理已初始化:', { providerId: this.providerId, model: this.model })
  }

  async _streamRequest(messages, options = {}, onContent) {
    console.log('LLM 代理: Starting stream request...', { messagesLength: messages.length })

    try {
      const response = await fetch(this.baseURL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          providerId: this.providerId,
          model: this.model,
          appId: this.appId,
          messages,
          options
        })
      })

      if (!response.ok) {
        const errorText = await response.text()
        console.error('LLM 代理: HTTP Error', response.status, errorText)
        throw new Error(`API请求失败: ${response.status} ${errorText}`)
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''

      while (true) {
        const { done, value } = await reader.read()
        if (done) {
          console.log('LLM 代理: Stream finished by server.')
          break
        }

        buffer += decoder.decode(value, { stream: true })

        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          const trimmedLine = line.trim()
          if (!trimmedLine) continue

          if (trimmedLine.startsWith('data:')) {
            const data = trimmedLine.substring(5).trim()

            if (data === '[DONE]') {
              console.log('LLM 代理: Received [DONE] signal.')
              return
            }

            try {
              const parsed = JSON.parse(data)
              const content = parsed.choices?.[0]?.delta?.content || ''
              if (content && onContent) {
                onContent(content)
              }
            } catch (e) {
              console.warn('LLM 代理: JSON parse error for line:', trimmedLine, e)
            }
          }
        }
      }
    } catch (err) {
      console.error('LLM 代理: Stream processing error:', err)
      throw err
    }
  }

  async generateContent(prompt, onContent, options = {}) {
    const systemPrompt = buildSystemPrompt(options.paradigm)

    return this._streamRequest([
      {
        role: 'system',
        content: systemPrompt
      },
      {
        role: 'user',
        content: prompt
      }
    ], { temperature: 0.7, ...options }, onContent)
  }

  async analyzeContent(text, onContent) {
    return this._streamRequest([
      {
        role: 'system',
        content: '你是一个专业的写作分析师，擅长分析文章的写作范式、结构和特点。请从以下几个方面分析文章：1. 主要写作范式类型 2. 文章结构特点 3. 语言风格特征 4. 目标读者群体 5. 写作技巧总结。请用简洁明了的语言回答，使用Markdown格式。'
      },
      {
        role: 'user',
        content: `请分析以下文章的写作范式：\n\n${text}`
      }
    ], { temperature: 0.3 }, onContent)
  }

  async extractStyle(text, onContent) {
    return this._streamRequest([
      {
        role: 'system',
        content: '你是一个专业的语言风格分析师。请分析给定文本的语言风格，并提取3-5个关键风格标签（如：#短句为主 #语气犀利 #大量隐喻 #数据支撑）。请直接输出标签，用空格分隔，不要有其他解释。'
      },
      {
        role: 'user',
        content: `请分析以下文本的风格：\n\n${text.substring(0, 2000)}`
      }
    ], { temperature: 0.2 }, onContent)
  }
}

export default DeepSeekAPI
