const axios = require('axios');
const crypto = require('crypto');
const fs = require('fs');

function generateSessionHash() {
  return crypto.randomBytes(6).toString('hex');
}

async function taoanhdep(prompt) {
  const sessionHash = generateSessionHash();
  const url1 = `https://taoanhdep.com/public/gg-dich.php?tukhoa=${encodeURIComponent(prompt)}`;
  const res1 = await axios.get(url1);
  if (res1.status !== 200 || !res1.data?.trim()) throw new Error("Không thể dịch prompt.");

  const text = res1.data;
  const url = 'https://heartsync-qwen-image-lora.hf.space/queue/join';

  await axios.post(url, {
    data: [prompt, 1953943649, true, 1024, 1024, 5],
    fn_index: 2,
    session_hash: sessionHash
  }, { headers: { 'Content-Type': 'application/json' } });

  const response = await axios.get(
    `https://heartsync-qwen-image-lora.hf.space/queue/data?session_hash=${sessionHash}`,
    { responseType: 'stream' }
  );

  return new Promise((resolve, reject) => {
    let buffer = "";
    const timeout = setTimeout(() => reject(new Error("Quá thời gian chờ tạo ảnh.")), 60000);

    response.data.on('data', chunk => {
      buffer += chunk.toString();
      const parts = buffer.split('\n\n');
      buffer = parts.pop();
      for (const ev of parts) {
        if (ev.startsWith("data: ")) {
          try {
            const parsed = JSON.parse(ev.slice(6));
            if (parsed.msg === "process_completed" && parsed.output?.data?.[0]?.url) {
              clearTimeout(timeout);
              return resolve(parsed.output.data[0].url);
            }
          } catch {}
        }
      }
    });

    response.data.on('end', () => { clearTimeout(timeout); reject(new Error("Không nhận được ảnh.")); });
    response.data.on('error', err => { clearTimeout(timeout); reject(err); });
  });
}

async function streamURL(url, ext = 'jpg') {
  const res = await axios.get(url, { responseType: 'stream' });
  const filePath = `tmp_${Date.now()}.${ext}`;
  const writer = fs.createWriteStream(filePath);
  res.data.pipe(writer);
  return new Promise(resolve =>
    writer.on('finish', () => resolve({ stream: fs.createReadStream(filePath), path: filePath }))
  );
}

module.exports.zuckbotconfig = {
  name: "img",
  version: "1.0.2",
  role: 0,
  author: "Thanh Tuấn",
  info: "Tạo ảnh từ prompt",
  Category: "Tiện ích",
  usages: "[prompt]",
  cd: 5
};

module.exports.onRun = async ({ api, event, args }) => {
  if (!args.length) return api.sendMessage("Vui lòng nhập prompt.", event.threadID, event.messageID);

  try {
    const imageUrl = await taoanhdep(args.join(" "));
    const { stream, path } = await streamURL(imageUrl);

    return api.sendMessage({ attachment: stream }, event.threadID, (err) => {
      try { fs.unlinkSync(path); } catch {}
      if (err) api.sendMessage("❌ Lỗi khi gửi ảnh.", event.threadID, event.messageID);
    }, event.messageID);

  } catch {
    return api.sendMessage("❌ Lỗi khi tạo ảnh, thử lại sau.", event.threadID, event.messageID);
  }
};