const axios = require("axios");
const fs = require("fs");
const path = require("path");

const BASE = "https://twannote.vercel.app";
const langByExt = e => ({
  js: "javascript", mjs: "javascript", cjs: "javascript",
  ts: "typescript", py: "python", json: "json",
  html: "html", htm: "html", css: "css",
  md: "markdown", sh: "bash", bash: "bash", txt: "text"
}[e] || "text");
const sendOf = o => m => new Promise(r =>
  o.api.sendMessage(m, o.event.threadID, (_, res) => r(res), o.event.messageID)
);

async function createNote(filePath) {
  const content = fs.readFileSync(filePath, "utf8");
  const title = path.basename(filePath);
  const language = langByExt(path.extname(filePath).slice(1).toLowerCase());
  const { data } = await axios.post(`${BASE}/api/code`, { title, content, language }, { timeout: 20_000 });
  const id = data?.id; if (!id) throw new Error("API trả về không có id");
  return { id, raw: `${BASE}/code/${id}/raw`, page: `${BASE}/code/${id}` };
}

this.zuckbotconfig = {
  name: "note",
  version: "2.0.0",
  role: 90,
  author: "twan",
  info: "notdbhdndnfnfjfjfnfnfnne",
  Category: "Tiện ích",
  usages: "..",
  cd: 5
};

this.onRun = async function (o) {
  const s = sendOf(o), name = this.zuckbotconfig.name;
  const file = path.join(__dirname, o.args[0] || "");
  try {
    const { id, raw, page } = await createNote(file);
    const res = await s(
      `📝 Đã tạo note
• Raw: ${raw}
• Page: ${page}
────────────────
📄 Nguồn: ${file}

📌 Thả cảm xúc để **tải Raw và ghi đè** file.`
    );
    global.zuckbot.onReaction.push({ ...res, name, path: file, o, url: raw, action: "confirm_from_url" });
  } catch (e) { console.error(e); s(String(e)); }
};

this.onReaction = async function (o) {
  const _ = o.onReaction, s = sendOf(o);
  try {
    if (o.event.userID !== _.o.event.senderID) return;
    if (_.action === "confirm_from_url") {
      const { data } = await axios.get(_.url, { responseType: "text", timeout: 20_000 });
      fs.writeFileSync(_.path, data);
      s(`✅ Đã ghi đè file\n🔗 ${_.path}`);
    }
  } catch (e) { console.error(e); s(String(e)); }
};