
const axios = require('axios');
const fs = require('fs');
const pathLib = require('path');

const BASE_URL = 'https://twannote.vercel.app'; 

function detectLanguageByExt(filePath) {
  const ext = pathLib.extname(filePath).slice(1).toLowerCase();
  const map = {
    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'
  };
  return map[ext] || 'text';
}

async function createNoteOnAPI(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  const title = pathLib.basename(filePath);
  const language = detectLanguageByExt(filePath);

  const res = await axios.post(`${BASE_URL}/api/code`, {
    title,
    content,
    language
  }, { timeout: 20000 });

  const id = res.data?.id;
  if (!id) throw new Error('API trả về không có id');

  const rawUrl = `${BASE_URL}/code/${id}/raw`;
  const viewUrl = `${BASE_URL}/api/code/${id}`;   // JSON view
  const pageUrl = `${BASE_URL}/code/${id}`;       // nếu có trang UI /code/:id

  return { id, rawUrl, viewUrl, pageUrl };
}

this.zuckbotconfig = {
  name: 'note',
  version: '2.3.1.3-api',
  author: "Nguyễn Thanh Mài",
  role: 2,
  info: `${BASE_URL}/code/:id`,
  Category: 'Admin',
  cd: 3,
  shadowPrefix: false,
  image: []
};

this.onRun = async function (o) {
  const name = this.zuckbotconfig.name;
  const maybeUrl = o.event?.messageReply?.args?.[0] || o.args[1];
  let targetPath = `${__dirname}/${o.args[0]}`;
  const send = msg => new Promise(r => o.api.sendMessage(msg, o.event.threadID, (err, res) => r(res), o.event.messageID));

  try {
    if (/^https?:\/\//i.test(maybeUrl)) {
      return send(`🔗 URL: ${maybeUrl}\n📄 File đích: ${targetPath}\n\nThả cảm xúc để **xác nhận** thay thế nội dung file từ URL này.`).then(res => {
        res = {
          ...res,
          name,
          path: targetPath,
          o,
          url: maybeUrl,
          action: 'confirm_replace_content_from_url',
        };
        global.zuckbot.onReaction.push(res);
      });
    }

    if (!fs.existsSync(targetPath)) {
      return send(`❎ Đường dẫn file không tồn tại để upload: ${targetPath}`);
    }

    const { id, rawUrl, viewUrl, pageUrl } = await createNoteOnAPI(targetPath);

    return send(
      `📝 Đã tạo note trên API\n` +
      `• ID: ${id}\n` +
      `• Raw: ${rawUrl}\n` +
      `• JSON: ${viewUrl}\n` +
      `• Page: ${pageUrl}\n` +
      `────────────────\n` +
      `📄 File nguồn: ${targetPath}\n\n` +
      `📌 Thả cảm xúc để **tải nội dung từ Raw về và ghi đè** file nguồn.`
    ).then(res => {
      res = {
        ...res,
        name,
        path: targetPath,
        o,
        url: rawUrl,
        action: 'confirm_replace_content_from_url',
      };
      global.zuckbot.onReaction.push(res);
    });

  } catch (e) {
    console.error(e);
    send(e.toString());
  }
};

this.onReaction = async function (o) {
  const _ = o.onReaction;
  const send = msg => new Promise(r => o.api.sendMessage(msg, o.event.threadID, (err, res) => r(res), o.event.messageID));

  try {
    if (o.event.userID != _.o.event.senderID) return;

    switch (_.action) {
      case 'confirm_replace_content_from_url': {
        const content = (await axios.get(_.url, { responseType: 'text', timeout: 20000 })).data;
        fs.writeFileSync(_.path, content);
        send(`✅ Đã ghi đè nội dung file\n\n🔗 File: ${_.path}`);
      } break;

      default:
        break;
    }
  } catch (e) {
    console.error(e);
    send(e.toString());
  }
};