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

class DeepSeekAPI {
  constructor(config) {
    this.baseURL = config.url
    this.apiKey = config.key
    this.model = config.model || 'deepseek-chat'
    this.appId = config.appId || ''  // 千帆大模型需要
    console.log('DeepSeekAPI 已初始化:', { baseURL: this.baseURL, model: this.model })
  }

  async _streamRequest(messages, options = {}, onContent) {
    const authHeader = this.apiKey.trim().startsWith('Bearer ')
      ? this.apiKey.trim()
      : `Bearer ${this.apiKey.trim()}`;

    // 构建 headers
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': authHeader
    }

    // 千帆大模型需要 appid header
    if (this.appId) {
      headers['appid'] = this.appId
    }

    console.log('DeepSeekAPI: Starting stream request...', { messagesLength: messages.length })

    try {
      const response = await fetch(this.baseURL, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          model: this.model,
          messages,
          stream: true,
          ...options
        })
      })

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

      console.log('DeepSeekAPI: Stream connection established.')

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

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

        buffer += decoder.decode(value, { stream: true })
        
        // Split by newline
        let lines = buffer.split('\n')
        // Keep the last part (potential incomplete line) in buffer
        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() // Remove 'data:' prefix
            
            if (data === '[DONE]') {
              console.log('DeepSeekAPI: Received [DONE] signal.')
              return
            }

            try {
              const parsed = JSON.parse(data)
              const content = parsed.choices?.[0]?.delta?.content || ''
              if (content) {
                // console.log('DeepSeekAPI: Received content chunk:', content.length) // Too verbose for large text
                if (onContent) {
                  onContent(content)
                }
              }
            } catch (e) {
              console.warn('DeepSeekAPI: JSON parse error for line:', trimmedLine, e)
            }
          }
        }
      }
    } catch (err) {
      console.error('DeepSeekAPI: Stream processing error:', err);
      throw err;
    }
  }

  async generateContent(prompt, onContent, options = {}) {
    // 构建系统提示词（支持范式专用 Prompt）
    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)}` // Limit context length
      }
    ], { temperature: 0.2 }, onContent)
  }
}

export default DeepSeekAPI
