"use strict";

const axios = require("axios");
const fs = require("fs");
const path = require("path");
const os = require("os");
const { once } = require("events");

module.exports.zuckbotconfig = {
  name: "theme",
  version: "1.4.2",
  role: 0,
  author: "Twan",
  info: "Tạo theme AI (preview) + gửi ảnh sáng/tối, áp dụng qua reply",
  Category: "Admin",
  usages: "[prompt]",
  cd: 5,
  shadowPrefix: true
};

// helpers
const tmp = p => path.join(os.tmpdir(), p);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const themeAsync = (api, threadID, opts) =>
  new Promise((res, rej) => api.theme(threadID, opts, (e, d) => (e ? rej(e) : res(d))));
const sendAsync = (api, threadID, msg, replyTo) =>
  new Promise(r => api.sendMessage(msg, threadID, (_, info) => r(info), replyTo));

// --- FIX(1): thêm header fbcdn
const HTTP_HEADERS = {
  "User-Agent": "Mozilla/5.0",
  "Referer": "https://www.facebook.com/"
};

async function download(url) {
  if (!url) return null;
  const file = tmp(`theme_${Date.now()}_${Math.random().toString(36).slice(2)}.jpg`);
  try {
    const res = await axios.get(url, { responseType: "stream", timeout: 20000, headers: HTTP_HEADERS });
    const w = fs.createWriteStream(file);
    res.data.pipe(w);
    await once(w, "finish");
    return file;
  } catch {
    try { fs.unlinkSync(file); } catch {}
    return null;
  }
}

function card(name, id) {
  return `[# THEME AI PREVIEW]\n\nName: ${name || "Không tên"}\nID: ${id}\n\n→ Reply "s" để áp dụng chủ đề này\n→ Reply prompt để tạo lại chủ đề`;
}

function pickPreviewUrls(gen) {
  const light = gen.lightUrl || gen.iconLight || gen.iconUrl || null;
  const dark  = gen.darkUrl  || gen.iconDark  || gen.iconUrl || null;
  return { light, dark };
}

async function attachPreview(gen) {
  const files = [];
  const { light, dark } = pickPreviewUrls(gen);
  const fLight = await download(light);
  const fDark  = await download(dark);
  if (fLight) files.push(fs.createReadStream(fLight));
  if (fDark)  files.push(fs.createReadStream(fDark));
  return { files, paths: [fLight, fDark].filter(Boolean) };
}

function getReplyStore() {
  global.zuckbot = global.zuckbot || {};
  global.zuckbot.onReply = global.zuckbot.onReply || [];
  return global.zuckbot.onReply;
}
function pushHandleReply(ctx) {
  const store = getReplyStore();
  store.push(ctx);
}
function replaceHandleReplyByMsgID(oldMsgID, nextCtx) {
  const store = getReplyStore();
  const next = store.filter(h => h.messageID !== oldMsgID);
  next.push(nextCtx);
  global.zuckbot.onReply = next;
}

async function safeUnlinkMany(paths) {
  for (const p of paths) {
    try { fs.unlinkSync(p); } catch {}
  }
}

module.exports.onRun = async function ({ api, event, args }) {
  const threadID = event.threadID;
  const prompt = args.length ? args.join(" ") : "anime";

  try {
    const gen = await themeAsync(api, threadID, { aiPrompt: prompt, dryRun: true });
    const { files, paths } = await attachPreview(gen);

    const info = await sendAsync(
      api,
      threadID,
      { body: card(gen.themeName, gen.themeId), attachment: files.length ? files : undefined },
      event.messageID
    );

    await sleep(100);
    await safeUnlinkMany(paths);

    if (info?.messageID) {
      pushHandleReply({
        name: module.exports.zuckbotconfig.name,
        messageID: info.messageID,
        author: event.senderID,
        threadID,
        themeId: gen.themeId,
        type: "_handleReply"
      });
    }
  } catch (e) {
    return api.sendMessage(`❌ Lỗi tạo theme: ${e?.message || e}`, threadID, undefined, event.messageID);
  }
};

module.exports.onReply = async function ({ api, event, onReply }) {
  if (!onReply || event.threadID !== onReply.threadID) return;
  if (event.senderID !== onReply.author) return;

  const text = (event.body || "").trim();
  if (!text) return;

  if (text.toLowerCase() === "s") {
    try {
      await themeAsync(api, onReply.threadID, { themeId: onReply.themeId });
      return api.sendMessage(`✅ Đã áp dụng chủ đề ID: ${onReply.themeId}`, onReply.threadID);
    } catch (e) {
      return api.sendMessage(`❌ Lỗi áp dụng: ${e?.message || e}`, onReply.threadID);
    }
  }

  try {
    const gen = await themeAsync(api, onReply.threadID, { aiPrompt: text, dryRun: true });
    const { files, paths } = await attachPreview(gen);

    const info = await sendAsync(api, onReply.threadID, {
      body: card(gen.themeName, gen.themeId),
      attachment: files.length ? files : undefined
    });

    await sleep(100);
    await safeUnlinkMany(paths);

    if (info?.messageID) {
      replaceHandleReplyByMsgID(
        onReply.messageID,
        {
          name: module.exports.zuckbotconfig.name,
          messageID: info.messageID,
          author: event.senderID,
          threadID: onReply.threadID,
          themeId: gen.themeId,
          type: "_handleReply"
        }
      );
    }
  } catch (e) {
    return api.sendMessage(`❌ Lỗi tạo lại theme: ${e?.message || e}`, onReply.threadID);
  }
};