this.zuckbotconfig = {
  name: "catbox",
  version: "3.0.0",
  author: "Nguyễn Thanh Tuấn",
  role: 0,
  aliases: ["upcat"],
  info: "Upload ảnh, gif, mp3 lên Catbox (hỗ trợ stream, retry, worker, chunk)",
  Category: "Tiện ích",
  usePrefix: false,
  cd: 0,
  shadowPrefix: false,
  image: []
};

this.onRun = async ({ api, event }) => {
  const axios = require("axios");
  const FormData = require("form-data");
  const https = require("https");
  const fs = require("fs");
  const { Worker } = require("worker_threads");

  if (!event.messageReply?.attachments?.length) {
    return api.sendMessage("Bạn chưa gửi ảnh, gif, mp3!", event.threadID, event.messageID);
  }

  // 🔄 Dynamic Connection Pool
  const agent = new https.Agent({ keepAlive: true });

  // 🔁 Adaptive Retry
  async function retryRequest(fn, maxAttempts = 5, baseDelay = 1000, maxDelay = 20000) {
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        return await fn();
      } catch (err) {
        if (attempt === maxAttempts) throw err;
        let delay = Math.min(baseDelay * 2 ** (attempt - 1), maxDelay);
        delay += Math.random() * (delay / 2); // jitter
        await new Promise(r => setTimeout(r, delay));
      }
    }
  }

  const links = [];

  for (const attachment of event.messageReply.attachments) {
    const validTypes = ["photo", "video", "audio", "animated_image"];
    if (!validTypes.includes(attachment.type)) continue;

    const ext = attachment.type === "photo" ? "png"
              : attachment.type === "animated_image" ? "gif"
              : attachment.type === "video" ? "mp4"
              : "mp3";

    try {
      // 🗜 Stream Processing: tải file qua stream
      const response = await axios.get(attachment.url, {
        responseType: "stream",
        httpsAgent: agent
      });

      // Nếu file lớn hơn 20MB → dùng Parallel Chunked Upload
      let size = parseInt(attachment.size || 0);
      if (size > 20 * 1024 * 1024) {
        console.log(`⚡ Dùng Chunked Upload cho file lớn (${(size/1024/1024).toFixed(1)}MB)`);

        const chunks = Math.ceil(size / (5 * 1024 * 1024)); // 5MB/chunk
        const promises = [];

        for (let i = 0; i < chunks; i++) {
          promises.push(new Promise((resolve, reject) => {
            const worker = new Worker(`
              const { parentPort, workerData } = require("worker_threads");
              const axios = require("axios");
              const FormData = require("form-data");
              const fs = require("fs");

              (async () => {
                const { url, start, end, index, ext } = workerData;
                const res = await axios.get(url, { responseType: "stream", headers: { Range: \`bytes=\${start}-\${end}\` } });
                const form = new FormData();
                form.append("reqtype", "fileupload");
                form.append("userhash", "");
                form.append("fileToUpload", res.data, \`chunk_\${index}.\${ext}\`);
                const upload = await axios.post("https://catbox.moe/user/api.php", form, { headers: form.getHeaders() });
                parentPort.postMessage(upload.data);
              })();
            `, { eval: true, workerData: { url: attachment.url, start: i*5*1024*1024, end: Math.min((i+1)*5*1024*1024-1, size), index: i, ext } });
            worker.on("message", resolve);
            worker.on("error", reject);
          }));
        }

        const results = await Promise.all(promises);
        links.push(...results);

      } else {
        // File nhỏ → upload trực tiếp với retry
        const form = new FormData();
        form.append("reqtype", "fileupload");
        form.append("userhash", "");
        form.append("fileToUpload", response.data, `upload.${ext}`);

        const uploadResponse = await retryRequest(() =>
          axios.post("https://catbox.moe/user/api.php", form, {
            headers: form.getHeaders(),
            httpsAgent: agent,
            timeout: 30000
          })
        );

        const data = uploadResponse.data;
        if (data.startsWith("Error:")) {
          api.sendMessage("❌ Lỗi khi upload: " + data, event.threadID, event.messageID);
        } else {
          links.push(data);
        }
      }

    } catch (err) {
      api.sendMessage(`❌ Upload thất bại: ${err.message}`, event.threadID, event.messageID);
    }
  }

  if (!links.length) {
    return api.sendMessage("Không có file hợp lệ để upload!", event.threadID, event.messageID);
  }

  return api.sendMessage("✅ Link Catbox:\n" + links.join("\n"), event.threadID, event.messageID);
};