import {
  defineCodeRunnersSetup,
  CodeRunnerContext,
  CodeRunnerOutput,
} from "@slidev/types";
import sanitizeHtml from "sanitize-html";
import axios from "axios";

const compileRequest = async (url: string, data: any) => {
  try {
    // 配置后端接口地址（请替换为你的实际接口地址）
    const res = await axios.post(url, JSON.stringify(data), {
      // 可选：请求配置（超时时间、请求头等）
      timeout: 3000,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    // 正确返回：{"rid":"694ce4e7a54e781b021cad2b","url":"/record/694ce4e7a54e781b021cad2b"}
    // 错误返回： {"error":{"message":"This language is not allowed to submit.","params":[],"stack":""}}

    if (res.url !== null) {
      // 返回token和用户信息（用于后续存储）
      return { success: true, msg: res };
    } else {
      console.log("result: " + JSON.stringify(res));
      // 后端返回业务错误（如账号不存在、密码错误）
      return {
        success: false,
        msg: res.error.message,
      };
    }
  } catch (error) {
    // 捕获网络错误、接口异常等
    return {
      success: false,
      msg: "网络异常，请稍后再试",
    };
  }
};

async function executeCppCodeRemotely(
  url: string,
  code: string,
  ctx: CodeRunnerContext
): Promise<CodeRunnerOutput> {
  const reqData = {
    lang: "cc.cc14",
    code: code,
  };

  const resp = await compileRequest(url, reqData);

  if (!resp.success) {
    return {
      html: "执行错误. res: " + resp.msg,
    };
  }

  return {
    html: "<h1>" + resp.msg + "</h5>",
  };
}

export default defineCodeRunnersSetup(() => {
  return {
    async cpp(code, ctx) {
      // 以某种方式执行代码并获取输出
      const result = await executeCppCodeRemotely(url, code, ctx);
      return {
        text: result,
      };
    },
    html(code, ctx) {
      return {
        html: sanitizeHtml(code),
      };
    },
  };
});
