export interface TestChatMessage {
  role: string;
  content: string;
}

export class TestChatCompletion {
  messageList: Array<TestChatMessage>;

  constructor(messageList: Array<TestChatMessage>) {
    this.messageList = messageList;
  }

  async createCompletionByStream(onDelta: (delta: string) => void) {
  const token = localStorage.getItem("r:70421cdd80237796d152de92a9d30276");
    if (!token) throw new Error('Token 未设置，请先存入 localStorage.token');

    const bodyJson = {
      token: `Bearer ${token}`,
      messages: this.messageList,
      model: 'fmode-4.5-128k',
      temperature: 0.5,
      presence_penalty: 0,
      frequency_penalty: 0,
      top_p: 1,
      stream: true,
    };

    const response = await fetch("https://server.fmode.cn/api/apig/aigc/gpt/v1/chat/completions", {
      headers: {
        accept: "text/event-stream",
      },
      method: "POST",
      body: JSON.stringify(bodyJson),
    });

    if (!response.body) throw new Error("流式响应失败");

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

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      const lines = buffer.split("\n");
      for (let i = 0; i < lines.length - 1; i++) {
        const line = lines[i].trim();
        if (line.startsWith("data:")) {
          const dataText = line.replace(/^data:\s*/, "");
          if (dataText === "[DONE]") return;
          try {
            const json = JSON.parse(dataText);
            const delta = json.choices?.[0]?.delta?.content;
            if (delta) onDelta(delta);
          } catch {
            // 忽略解析错误
          }
        }
      }
      buffer = lines[lines.length - 1];
    }
  }
}
