import axios from "@/services/config"
import { v4 as uuidv4 } from 'uuid'
import { fetchEventSource } from '@microsoft/fetch-event-source'

interface ChatParams {
  model: string;
  temperature: number;
  max_tokens: number;
  top_p: number;
  frequency_penalty: number;
  presence_penalty: number;
  messages: Array<{ role: string; content: string }>;
  uid: string;
  mind_map_question: string;
  stream: boolean;
  response_format: { type: string };
}

const DEFAULT_PARAMS: Omit<ChatParams, 'messages' | 'uid'> = {
  model: "gpt-4o-2024-11-20",
  temperature: 0,
  max_tokens: 4096,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
  mind_map_question: "",
  stream: false,
  response_format: { type: "text" }
};

export const chat_no_stream = async (msg: string): Promise<string> => {
  const params: ChatParams = {
    ...DEFAULT_PARAMS,
    messages: [{ role: "user", content: msg }],
    uid: uuidv4(),
    stream: false
  };

  try {
    const res = await axios.post('https://appapi.cocorobo.cn/api/common/chat', params);
    let content = res.FunctionResponse.choices[0].message.content;

    // 清理可能的 markdown 格式
    if (content.includes('```json')) {
      // 提取 ```json 和 ``` 之间的内容
      const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/);
      if (jsonMatch) {
        content = jsonMatch[1].trim();
      }
    } else if (content.includes('```')) {
      // 提取 ``` 和 ``` 之间的内容
      const codeMatch = content.match(/```\s*([\s\S]*?)\s*```/);
      if (codeMatch) {
        content = codeMatch[1].trim();
      }
    }

    return content
  } catch (err) {
    throw err;
  }
};

export const chat_stream = async (
  msg: string,
  onMessage: (event: { type: 'message' | 'close' | 'error' | 'messageEnd'; data: string }) => void
): Promise<void> => {
  const params: ChatParams = {
    ...DEFAULT_PARAMS,
    messages: [{ role: "user", content: msg }],
    uid: uuidv4(),
    stream: true
  };

  const ctrl = new AbortController();
  let content = ''
  try {
    await fetchEventSource('https://appapi.cocorobo.cn/api/common/chat', {
      method: 'POST',
      body: JSON.stringify(params),
      signal: ctrl.signal,
      headers: {
        'Content-Type': 'application/json',
      },
      onmessage(event) {
        let data = JSON.parse(event.data)
        if (data.content) {
          if (data.content != '[DONE]') {
            content += data.content
            onMessage({
              type: 'message',
              data: content
            });
          }else{
            onMessage({
              type: 'messageEnd',
              data: content
            });
          }

        }
      },
      onclose() {
        onMessage({
          type: 'close',
          data: 'SSE Connection closed'
        });
      },
      onerror(err) {
        onMessage({
          type: 'error',
          data: err.message || 'Unknown error'
        });
        // 返回 undefined 以阻止自动重连，如需重连则删除此行
        throw err;
      },
    });
  } finally {
    ctrl.abort();
  }
};
