// API配置文件
export const API_CONFIG = {
  // DeepSeek API配置
  DEEPSEEK: {
    BASE_URL: 'https://api.deepseek.com/v1',
    MODEL: 'deepseek-chat',
    API_KEY:
      process.env.UMI_APP_DEEPSEEK_API_KEY ||
      process.env.REACT_APP_DEEPSEEK_API_KEY ||
      'your-api-key-here',
    MAX_TOKENS: 2000,
    TEMPERATURE: 0.7,
    SYSTEM_PROMPT: '你是一个智能AI助手，请用简洁、专业、友好的方式回答用户的问题。'
  },
  
  // 其他API配置
  OPENAI: {
    BASE_URL: 'https://api.openai.com/v1',
    MODEL: 'gpt-3.5-turbo',
    API_KEY: process.env.UMI_APP_OPENAI_API_KEY || '',
    MAX_TOKENS: 2000,
    TEMPERATURE: 0.7
  }
}

// 调试：开发阶段临时查看是否拿到
if (process.env.NODE_ENV === 'development') {
  // 只显示是否存在，不打印具体 key
  // eslint-disable-next-line no-console
  console.log(
    'DeepSeek key loaded =',
    !!process.env.UMI_APP_DEEPSEEK_API_KEY
  )
}

// DeepSeek 调用
export const callDeepSeekAPI = async (messages, options = {}) => {
  const cfg = API_CONFIG.DEEPSEEK
  const apiKey = cfg.API_KEY
  if (!apiKey || apiKey === 'your-api-key-here') {
    throw new Error('NO_API_KEY')
  }

  // 组装消息（如果历史里已经含 system 就不重复）
  const hasSystem = messages.some(m => m.role === 'system')
  const finalMessages = hasSystem
    ? messages
    : [{ role: 'system', content: cfg.SYSTEM_PROMPT }, ...messages]

  const payload = {
    model: cfg.MODEL,
    messages: finalMessages.map(m => ({ role: m.role, content: m.content })),
    temperature: options.temperature ?? cfg.TEMPERATURE,
    max_tokens: options.maxTokens ?? cfg.MAX_TOKENS,
    stream: false
  }

  const resp = await fetch(`${cfg.BASE_URL}/chat/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${apiKey}`
    },
    body: JSON.stringify(payload)
  })

  const data = await resp.json().catch(() => ({}))

  if (!resp.ok) {
    // 统一抛出，交给 handleAPIError
    const msg = data?.error?.message || resp.statusText || 'API_ERROR'
    const err = new Error(msg)
    err.status = resp.status
    err.code = data?.error?.code
    throw err
  }

  const content = data?.choices?.[0]?.message?.content?.trim()
  if (!content) throw new Error('EMPTY_RESPONSE')
  return content
}



// 本地服务调用 - 非流式
export const callLocalChatAPI = async (prompt, onStreamData) => {
  const base = '/api/chat/stream'
  const url = `${base}?prompt=${encodeURIComponent(prompt)}`

  try {
    const resp = await fetch(url, { method: 'GET' })

    if (!resp.ok) {
      const txt = await resp.text().catch(() => null)
      const msg = txt || resp.statusText || `HTTP_${resp.status}`
      const err = new Error(msg)
      err.status = resp.status
      throw err
    }

    //等待完整响应
    const responseText = await resp.text()
    // console.log('API response text:', responseText) 


    // 解析响应内容
    let thoughtContent = ''
    let messageContent = ''
    let currentEvent = ''

    // 按行处理响应
    const lines = responseText.split(/\r?\n/)
    console.log('总行数:', lines.length)
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i]
      
      if (line.startsWith('event:')) {
        currentEvent = line.substring(6).trim()
        console.log(`第${i}行 - 事件类型:`, currentEvent)
      } else if (line.startsWith('data:')) {
        const data = line.substring(5)
        console.log(`第${i}行 - 数据类型:${currentEvent}, 数据长度:${data.length}, 数据内容:${data.substring(0, 50)}...`)
        
        if (currentEvent === 'thought') {
          thoughtContent += data
        } else if (currentEvent === 'message') {
          // 累加所有 message 数据，而不是只处理第一个
          messageContent += data
          console.log(`messageContent 当前长度: ${messageContent.length}`)
        }
      }
    }

    // 调试：打印解析结果
    console.log('解析结果:', { 
      thoughtLength: thoughtContent.length, 
      messageLength: messageContent.length,
      thought: thoughtContent.substring(0, 100) + '...',
      message: messageContent.substring(0, 100) + '...'
    })

    // 返回最终结果
    console.log('API returning:3333', { thought: thoughtContent, message: messageContent }) // 调试信息
    
    // 确保返回的内容不为undefined
    return {
      thought: thoughtContent || '',
      message: messageContent || ''
    }

  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('[callLocalChatAPI] ERROR:', err)
    throw err
  }
}

// 错误处理函数
export const handleAPIError = (error) => {
  const raw = error?.message || ''
  const status = error?.status
  const code = error?.code

  if (raw === 'NO_API_KEY') return '未配置 API Key，请在 .env 里加 UMI_APP_DEEPSEEK_API_KEY 并重启。'
  if (raw === 'EMPTY_RESPONSE') return '接口返回空结果，请重试。'

  // 典型鉴权问题
  if (status === 401 || /unauthorized|invalid api key/i.test(raw) || code === 'invalid_api_key') {
    return 'API密钥无效，请检查是否正确。'
  }

  if (status === 429 || /rate limit/i.test(raw)) return '请求过多，被限流。'
  if (status === 500) return '服务端错误，请稍后再试。'
  if (/timeout/i.test(raw)) return '请求超时，请检查网络。'
  if (/certificate|SSL/i.test(raw)) return '证书/网络问题，请更换网络或代理。'

  return `调用失败：${raw || '未知错误'}`
}
