import { existsSync, readFileSync, writeFileSync } from "node:fs";
import client from "@/lib/client";

const path = `${import.meta.dirname}/../../memory.json`;

class MemoryClass {
  private cachedMemory: any;

  constructor() {
    if (!existsSync(path)) {
      writeFileSync(path, JSON.stringify({
        processedInfo: [],
        permissions: {},
        lastReadMention: 0,
        lastReadReply: 0,
        userid: "",
        max_length: 0,
      }));
    }
  }

  get memory() {
    return JSON.parse(readFileSync(path, "utf-8"));
  }

  set memory(data: any) {
    writeFileSync(path, JSON.stringify(data), "utf-8");
  }
}

const Memory = new MemoryClass();

export const initData = async () => {
  await Promise.all([
    (async () => {
      const response = await client.request("me/");

      if (!response.success)
        throw new Error("meの取得に失敗しました");

      const mem = Memory.memory;
      mem.userid = response.userid;
      Memory.memory = mem;
    })(),
    (async () => {
      const response = await client.request("serverinfo-api");

      const mem = Memory.memory;
      mem.max_length = response.server_info.max_ueuse_length;
      Memory.memory = mem;
    })(),
  ]);
}

export default Memory;