const AI_API_KEY = process.env.ZHIPU_API_KEY || process.env.DASHSCOPE_API_KEY || ''
const AI_API_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'

interface AIMessage {
  role: 'system' | 'user' | 'assistant'
  content: string
}

export async function callAI(messages: AIMessage[], temperature = 0.3): Promise<string> {
  const resp = await fetch(AI_API_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${AI_API_KEY}`,
    },
    body: JSON.stringify({
      model: 'qwen-plus',
      messages,
      temperature,
      max_tokens: 4096,
    }),
  })

  if (!resp.ok) {
    const errText = await resp.text()
    throw new Error(`AI API error ${resp.status}: ${errText}`)
  }

  const data = await resp.json()
  return data.choices?.[0]?.message?.content || ''
}

export async function callAIJSON(messages: AIMessage[], temperature = 0.3): Promise<any> {
  const raw = await callAI(messages, temperature)
  console.log('[AI] raw response length:', raw.length)
  // 提取JSON块（兼容```json包裹）
  let jsonStr = raw.trim()
  const codeBlockMatch = raw.match(/```(?:json)?\s*([\s\S]*?)```/)
  if (codeBlockMatch) {
    jsonStr = codeBlockMatch[1].trim()
  } else {
    // 找第一个[或{到最后一个]或}
    const firstBracket = raw.search(/[[{]/)
    if (firstBracket >= 0) {
      const lastBracket = Math.max(raw.lastIndexOf(']'), raw.lastIndexOf('}'))
      if (lastBracket > firstBracket) {
        jsonStr = raw.substring(firstBracket, lastBracket + 1).trim()
      }
    }
  }
  try {
    return JSON.parse(jsonStr)
  } catch (e) {
    // AI可能返回多个独立JSON对象（非数组格式），尝试包装成数组
    try {
      // 将相邻的}{替换为},{
      const arrayStr = '[' + jsonStr.replace(/\}\s*\{/g, '},{') + ']'
      return JSON.parse(arrayStr)
    } catch (e2) {
      console.error('[AI] JSON parse failed. Raw (500 chars):', raw.substring(0, 500))
      throw e2
    }
  }
}
