import { PluginFactory } from "@tingwujs/core-asr";
import { nanoid } from "nanoid";
import { eSpeechRecognitionStatusType } from "../hooks";
import { APP_ID } from "@tingwujs/service";

export const realtimeRecordCorrection = "tingwu-meeting-realtime";

export const getSendMessage = ({
  action,
  taskId,
  payload: sendPayload = {},
}: {
  action: "start" | "stop" | "continue";
  taskId: string;
  payload?: Record<string, any>;
}) => {
  let payload: Record<string, any> | undefined;
  if (action === "start") {
    payload = {
      model: realtimeRecordCorrection,
      task_group: "aigc",
      task: "multimodal-generation",
      function: "generation",
      input: {
        directive: "start", // 固定传（适配API）
        dataId: sendPayload.dataId,
        appId: APP_ID,
      },
    };
  }

  if (action === "continue") {
    payload = {
      model: realtimeRecordCorrection,
      task_group: "aigc",
      task: "multimodal-generation",
      function: "generation",
      input: {
        directive: "ping",
      },
    };
  }

  if (action === "stop") {
    payload = {
      model: realtimeRecordCorrection, // 预发固定填这个
      task_group: "aigc",
      task: "multimodal-generation",
      function: "generation",
      input: {
        directive: "stop", // 固定传（适配API）
      },
    };
  }

  return {
    header: {
      task_id: taskId,
      streaming: "duplex",
      action:
        action === "start" ? "run-task" : action === "continue" ? "continue-task" : "finish-task",
    },
    payload,
  };
};

export const RealtimeRecordPlugin: PluginFactory = config => {
  const { startPayload, setStatus, onMessage, onErrorMessage } = config;
  let taskId = "";
  return {
    onWsConnect(context) {
      const { connection } = context;

      taskId = nanoid(16);
      connection.send(
        JSON.stringify(getSendMessage({ taskId, action: "start", payload: startPayload }))
      );
      setStatus(eSpeechRecognitionStatusType.STARTING);
    },
    onError(_, data) {
      setStatus(eSpeechRecognitionStatusType.ERROR);
      console.info("socket: test-onError", data);
      onErrorMessage?.(data);
    },
    onMessage(context, data) {
      const { recorder, connection } = context;
      const resultData = JSON.parse(data.data);
      const { payload, header } = resultData;
      // 处理不同事件
      switch (payload?.output?.action) {
        case "speech-listen":
          recorder.start({ sampleRate: 16000 });
          break;
        case "recognize-result": {
          setStatus(eSpeechRecognitionStatusType.RECORDING);
          break;
        }
        case "task-failed":
          setStatus(eSpeechRecognitionStatusType.ERROR);
          recorder.stop();
          connection.close();
          break;
        case "speech-end":
          setStatus(eSpeechRecognitionStatusType.IDLE);
          recorder.stop();
          connection.close();
          break;
        default:
          console.log("socket 收到未知事件:", payload);
      }
      onMessage?.(resultData, context);
    },
  };
};
