import uwuzu from "better-uwuzu-sdk";
import config from "@/lib/config";
import Parser from "better-uwuzu-sdk/1.6.8/parser";
import ApiMap from "better-uwuzu-sdk/types/1.6.8/map";
import Memory from "@/lib/memory";
import { EOL } from "node:os";

const client = new uwuzu<ApiMap>({
  origin: config.uwuzu.origin,
  parser: Parser,
});

client.token = config.uwuzu.token;
export default client;

export const createUeuse = async (data: ApiMap["ueuse/create"]["body"], title: string) => {
  const mem = Memory.memory;
  const excessedMessage = "**👉返信に続きがあります。**";
  
  let lines = data.text.split(EOL);
  let firstUniqid = "";
  let count = 0;

  type ExtractSuccess<T> = T extends { success: true } ? T : never;
  const results: ExtractSuccess<ApiMap["ueuse/create"]["response"]>[] = [];

  while (lines.length > 0) {
    count++;
    let currentText = "";
    
    const currentMaxLength = (data.replyid !== undefined || firstUniqid !== "") 
      ? mem.max_length 
      : config.ueuse.maxLengthWithPublic === 0
        ? mem.max_length
        : config.ueuse.maxLengthWithPublic;

    const limit = currentMaxLength - (excessedMessage.length + EOL.length * 2);

    while (lines.length > 0) {
      const nextLine = lines[0];
      if (nextLine === undefined)
        break;

      if (nextLine.length > limit && currentText === "") {
        const targetLine = lines.shift() || "";
        currentText = targetLine.slice(0, limit);

        lines.unshift(targetLine.slice(limit));
        break;
      }

      const potentialText = currentText ? currentText + EOL + nextLine : nextLine;
      if (potentialText.length <= limit) {
        currentText = potentialText;
        lines.shift();
      } else {
        break;
      }
    }

    currentText = currentText.trimEnd();

    if (lines.length > 0) {
      currentText += EOL.repeat(2) + excessedMessage;
    }

    let postedUniqid = "";
    let success = false;

    for (let attempt = 1; attempt <= config.ueuse.maxRetries; attempt++) {
      const response = await client.request("ueuse/create", {
        ...data,
        text: currentText,
        replyid: data.replyid === undefined && firstUniqid !== ""
          ? firstUniqid
          : data.replyid,
      });

      if (response.success) {
        success = true;
        postedUniqid = response.uniqid;
        results.push(response);
        break;
      }

      console.warn(`${title}の投稿に失敗しました (試行 ${attempt}/${config.ueuse.maxRetries}):`, response.error_code);
      if (attempt < config.ueuse.maxRetries) {
        await new Promise(resolve => setTimeout(resolve, config.ueuse.retryInterval));
      }
    }

    if (!success) {
      console.error(`${title}の全試行が失敗したため、処理を中断します。`);
      break;
    }

    if (firstUniqid === "")
      firstUniqid = postedUniqid;

    console.log(`${title}を投稿(${count}):`, postedUniqid);

    while (lines.length > 0 && lines[0]?.trim() === "") {
      lines.shift();
    }
  }

  return results;
}