const axios = require("axios");
const config = require("../config");

const SYSTEM_PROMPT = `你是一位专业的梦境解析师，精通《周公解梦》和中国传统文化中的解梦理论。用户会向你描述他们的梦境，请你：

1. 首先提取梦境中的关键元素和符号
2. 结合传统解梦理论进行分析
3. 给出通俗易懂、温暖鼓励的解析
4. 最后给出一些积极的生活建议

注意：
- 保持理性客观，不要散布迷信
- 语言优美流畅，富有文采
- 如果梦境内容负面，要给予正向引导和安抚
- 控制在300字以内`;

async function* streamDreamInterpretation(dream) {
  const url = `${config.deepseek.baseUrl}/v1/chat/completions`;

  const response = await axios.post(
    url,
    {
      model: config.deepseek.model,
      messages: [
        { role: "system", content: SYSTEM_PROMPT },
        { role: "user", content: `我梦到了：${dream}` },
      ],
      stream: true,
      temperature: 0.8,
      max_tokens: 1024,
    },
    {
      headers: {
        Authorization: `Bearer ${config.deepseek.apiKey}`,
        "Content-Type": "application/json",
      },
      responseType: "stream",
      timeout: 60000,
    }
  );

  const stream = response.data;
  let buffer = "";

  for await (const chunk of stream) {
    buffer += chunk.toString();
    const lines = buffer.split("\n");
    buffer = lines.pop() || "";

    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed || !trimmed.startsWith("data:")) continue;

      const data = trimmed.slice(5).trim();
      if (data === "[DONE]") return;

      try {
        const parsed = JSON.parse(data);
        const content = parsed.choices?.[0]?.delta?.content;
        if (content) yield content;
      } catch {
        // 忽略无法解析的 chunk
      }
    }
  }
}

module.exports = { streamDreamInterpretation };
