File size: 30,527 Bytes
ddf2137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
import fs from 'fs';
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import axios from 'axios';
import fuzzy from 'fuzzy';
import { google } from 'googleapis';
import dotenv from 'dotenv';
import ytdl from '@distube/ytdl-core';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
globalThis.client = globalThis.client || { pendingCommands: new Map(), handleReply: [] };

const CONFIG = {
  cacheDir: path.join(__dirname, 'cache', 'dun'),
  contextPath: path.join(__dirname, 'cache', 'dun', 'context.json'),
  tempPath: path.join(__dirname, 'cache', 'dun', 'temp'),
  mp3Path: path.join(__dirname, 'cache', 'dun', 'mp3'),
  imagePath: path.join(__dirname, 'cache', 'dun', 'images'),
  commandsDir: path.join(__dirname, '..', '..'),
  maxHistory: 50,
  cacheDuration: 1800 * 1000,
  maxCacheSize: 300,
  maxMp3CacheSize: 30,
  maxImageSize: 5 * 1024 * 1024,
  maxFileSize: 20 * 1024 * 1024,
  apiTimeout: 10000,
  reactions: ['😎', '🚀', '🎉', '😘', '👋'],
  imageChance: 0.2,
  fuzzyThreshold: 0.8,
};

const API_KEYS = process.env.GEMINI_API_KEYS?.split(',') || ['AIzaSyCDzwltmCpZevJv3iKC0nsgQbgX3AhjjKc'];
let currentApiKeyIndex = 0;

class Cache {
  constructor() {
    this.gemini = new Map();
    this.mp3 = new Map();
    this.commands = new Map([['commands', { commands: [], timestamp: Date.now() }]]);
  }

  cleanup(maxSize, cache, isMp3 = false) {
    const now = Date.now();
    for (const [key, { timestamp, filePath }] of cache) {
      if (now - timestamp > CONFIG.cacheDuration) {
        FileHandler.cleanupTempFile(filePath);
        cache.delete(key);
      }
    }
    while (cache.size > maxSize) {
      const oldestKey = cache.keys().next().value;
      FileHandler.cleanupTempFile(cache.get(oldestKey).filePath);
      cache.delete(oldestKey);
    }
  }
}

const caches = new Cache();

class FileHandler {
  static ensureDir(dir) {
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  }

  static loadJSON(file) {
    this.ensureDir(path.dirname(file));
    if (!fs.existsSync(file)) return {};
    try {
      return JSON.parse(fs.readFileSync(file, 'utf8') || '{}') || {};
    } catch (e) {
      console.error(`Error loading JSON ${file}:`, e.stack);
      return {};
    }
  }

  static saveJSON(file, data) {
    this.ensureDir(path.dirname(file));
    try {
      fs.writeFileSync(file, JSON.stringify(data, null, 2));
    } catch (e) {
      console.error(`Error saving JSON ${file}:`, e.stack);
    }
  }

  static async loadCommands() {
    this.ensureDir(CONFIG.commandsDir);
    const commands = [];
    const scanDir = async dir => {
      for (const file of fs.readdirSync(dir, { withFileTypes: true })) {
        const fullPath = path.join(dir, file.name);
        if (file.isDirectory()) await scanDir(fullPath);
        else if (file.name.endsWith('.js') && file.name !== 'dun.js') {
          try {
            const cmd = (await import(pathToFileURL(fullPath).href)).default;
            if (cmd?.config?.name && cmd?.onRun) {
              commands.push({ ...cmd.config, path: fullPath, module: cmd });
            }
          } catch (e) {
            console.error(`Error loading command ${fullPath}:`, e.stack);
          }
        }
      }
    };
    await scanDir(CONFIG.commandsDir);
    caches.commands.set('commands', { commands, timestamp: Date.now() });
    return commands;
  }

  static cleanupTempFile(filePath) {
    try {
      if (filePath && fs.existsSync(filePath)) fs.unlinkSync(filePath);
    } catch (e) {
      console.error(`Error cleaning temp file ${filePath}:`, e.stack);
    }
  }
}

setInterval(async () => {
  try {
    caches.cleanup(CONFIG.maxCacheSize, caches.gemini);
    caches.cleanup(CONFIG.maxMp3CacheSize, caches.mp3, true);
    if ((caches.commands.get('commands')?.timestamp || 0) < Date.now() - 3600 * 1000) {
      await FileHandler.loadCommands();
    }
  } catch (e) {
    console.error('Error in cache cleanup:', e.stack);
  }
}, 60 * 60 * 1000);

async function checkAdminPermission(userID, threadID, api, isBot = false) {
  try {
    const threadInfo = await api.getThreadInfo(threadID).catch(e => {
      console.error(`Error fetching thread info ${threadID}:`, e.stack);
      return null;
    });
    if (!threadInfo?.adminIDs) return false;
    const targetID = isBot ? api.getCurrentUserID?.() : userID;
    return threadInfo.adminIDs.some(admin => admin.id === targetID);
  } catch (e) {
    console.error(`Error checking admin permission for ${userID}:`, e.stack);
    return false;
  }
}

async function executeGroupAction(api, threadID, action, value) {
  const actions = {
    image: async () => {
      const { data } = await axios.get(value, { responseType: 'stream', timeout: CONFIG.apiTimeout });
      await api.setThreadImage(data, threadID);
      return 'Ảnh nhóm mới xịn! 🖼️';
    },
    nickname: async () => {
      await api.changeNickname(value[1], threadID, value[0]);
      return `Đổi thành ${value[1]}! 😎`;
    },
    kick: async () => {
      await api.removeUserFromGroup(value, threadID);
      return 'Đã kick! 👋';
    },
    add: async () => {
      await api.addUserToGroup(value, threadID);
      return 'Thêm người mới! 🎉';
    },
    name: async () => {
      await api.setTitle(value, threadID);
      return `Tên nhóm mới là ${value}! 🎉`;
    },
    poll: async () => {
      await api.createPoll(value.question, value.options, threadID);
      return `Bình chọn "${value.question}" đã tạo! 🗳️`;
    },
    theme: async () => {
      await api.changeThreadTheme(value, threadID);
      return `Chủ đề mới ${value}! 🌈`;
    },
    emoji: async () => {
      await api.changeThreadEmoji(value, threadID);
      return `Icon nhóm mới ${value}! 😎`;
    },
  };

  try {
    if (!(await checkAdminPermission(null, threadID, api, true))) return 'Bot cần quyền admin! 😎';
    return await actions[action]?.() || 'Hành động không hỗ trợ! 😝';
  } catch (e) {
    console.error(`Error executing action ${action}:`, e.stack);
    return `Lỗi ${action}: ${e.message}! 😭`;
  }
}

async function resolveUserID(api, threadID, identifier, event) {
  try {
    if (!identifier) return event?.messageReply?.senderID || { error: 'Cần tên, @ hoặc UID! 😝' };
    const name = normalizeText(identifier.replace(/^@/, '')).trim();
    const threadInfo = await api.getThreadInfo(threadID).catch(e => {
      console.error(`Error fetching thread info ${threadID}:`, e.stack);
      return null;
    });
    if (!threadInfo?.userInfo) return { error: 'Không lấy được thông tin nhóm! 😕' };

    const matches = threadInfo.userInfo
      .map(user => ({
        id: user.id,
        name: user.name,
        nickname: threadInfo.nicknames?.[user.id],
        score: Math.max(
          fuzzy.test(name, normalizeText(user.name), { score: CONFIG.fuzzyThreshold }),
          threadInfo.nicknames?.[user.id] ? fuzzy.test(name, normalizeText(threadInfo.nicknames[user.id]), { score: CONFIG.fuzzyThreshold }) : 0
        ),
      }))
      .filter(user => user.score >= CONFIG.fuzzyThreshold)
      .sort((a, b) => b.score - a.score);

    if (matches.length === 1) return matches[0].id;
    if (matches.length > 1) return { error: `Tìm thấy ${matches.length} người: ${matches.map(m => m.name).join(', ')}. Dùng @tag hoặc reply! 😝` };
    if (identifier.match(/^\d+$/)) {
      const userInfo = await api.getUserInfo([identifier]).catch(e => {
        console.error(`Error fetching user info ${identifier}:`, e.stack);
        return {};
      });
      return userInfo[identifier]?.name ? identifier : { error: `Không tìm thấy UID "${identifier}"! 😕` };
    }
    return { error: `Không tìm thấy "${identifier}" trong nhóm! 😕` };
  } catch (e) {
    console.error(`Error resolving user ID "${identifier}":`, e.stack);
    return { error: `Lỗi tìm "${identifier}". Reply tin nhắn của họ! 😕` };
  }
}

async function getRandomImage() {
  try {
    const images = fs.readdirSync(CONFIG.imagePath).filter(f => /\.(jpg|jpeg|png|gif)$/i.test(f));
    if (images.length) {
      const filePath = path.join(CONFIG.imagePath, images[Math.floor(Math.random() * images.length)]);
      if (fs.statSync(filePath).size <= CONFIG.maxImageSize) return fs.createReadStream(filePath);
    }
    return (await axios.get('https://source.unsplash.com/random/200x200', { responseType: 'stream', timeout: 5000 })).data;
  } catch (e) {
    console.error('Error getting random image:', e.stack);
    return null;
  }
}

function loadChatHistory(uid) {
  const filePath = path.join(CONFIG.cacheDir, 'uids', `${uid}.json`);
  FileHandler.ensureDir(path.dirname(filePath));
  if (!fs.existsSync(filePath)) return [];
  try {
    return JSON.parse(fs.readFileSync(filePath, 'utf8') || '[]') || [];
  } catch (e) {
    console.error(`Error loading chat history ${uid}:`, e.stack);
    return [];
  }
}

function appendToChatHistory(uid, chatHistory) {
  FileHandler.saveJSON(path.join(CONFIG.cacheDir, 'uids', `${uid}.json`), chatHistory.slice(-CONFIG.maxHistory));
}

async function updateContext(uid, body, response, intent, lastBotMessage) {
  const context = FileHandler.loadJSON(CONFIG.contextPath);
  context[uid] = {
    intents: (context[uid]?.intents || []).concat({ body, response, intent, timestamp: Date.now() }).slice(-CONFIG.maxHistory),
    lastIntent: intent || 'casual',
    lastBotMessage: lastBotMessage || response,
  };
  FileHandler.saveJSON(CONFIG.contextPath, context);
}

async function searchSong(query) {
  try {
    const { data } = await axios.get(`https://www.youtube.com/results?search_query=${encodeURIComponent(query + ' song')}`, { timeout: CONFIG.apiTimeout });
    const videoIds = (data.match(/"videoId":"([^"]+)"/g) || []).map(id => id.match(/"videoId":"([^"]+)"/)[1]).slice(0, 3);
    const videos = await Promise.all(videoIds.map(id => ytdl.getInfo(`https://www.youtube.com/watch?v=${id}`).then(info => ({ url: info.videoDetails.video_url, title: info.videoDetails.title })).catch(() => null)));
    return videos.filter(Boolean).sort((a, b) => fuzzy.test(query, a.title) - fuzzy.test(query, b.title));
  } catch (e) {
    console.error(`Error searching song "${query}":`, e.stack);
    return [];
  }
}

async function downloadYouTubeAudio(url) {
  if (!ytdl.validateURL(url)) return { error: 'Link YouTube không hợp lệ! 😕' };
  const videoId = ytdl.getURLVideoID(url);
  const cacheKey = `youtube:${videoId}`;
  const tempPath = path.join(CONFIG.tempPath, `${videoId}_temp.mp3`);
  const filePath = path.join(CONFIG.mp3Path, `${videoId}_${Date.now()}.mp3`);

  if (caches.mp3.has(cacheKey) && fs.existsSync(caches.mp3.get(cacheKey).filePath)) {
    return { filePath: caches.mp3.get(cacheKey).filePath, fromCache: true };
  }

  FileHandler.ensureDir(CONFIG.mp3Path);
  try {
    await new Promise((resolve, reject) => {
      ytdl(url, { filter: 'audioonly', quality: 'lowestaudio' })
        .pipe(fs.createWriteStream(tempPath))
        .on('finish', resolve)
        .on('error', reject);
    });
    if (fs.statSync(tempPath).size > CONFIG.maxFileSize) throw new Error('File quá 20MB!');
    fs.renameSync(tempPath, filePath);
    if (caches.mp3.size >= CONFIG.maxMp3CacheSize) caches.mp3.delete(caches.mp3.keys().next().value);
    caches.mp3.set(cacheKey, { filePath, timestamp: Date.now() });
    return { filePath, fromCache: false };
  } catch (e) {
    console.error(`Error downloading audio ${url}:`, e.stack);
    FileHandler.cleanupTempFile(tempPath);
    return { error: `Lỗi tải nhạc: ${e.message}! 😭` };
  }
}

async function suggestThemeOrEmoji(description, type) {
  try {
    const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` });
    const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]);
    const prompt = `Gợi ý một ${type === 'theme' ? 'chủ đề (theme ID hoặc tên màu)' : 'emoji'} phù hợp với "${description}". Trả về chỉ một giá trị.`;
    const { data } = await genaiService.models.generateContent({
      model: 'models/gemini-1.5-pro-latest',
      requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 50, temperature: 0.7 } },
      auth,
    });
    return data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || (type === 'theme' ? 'blue' : '😎');
  } catch (e) {
    console.error(`Error suggesting ${type} for "${description}":`, e.stack);
    return type === 'theme' ? 'blue' : '😎';
  }
}

async function analyzeIntentWithGemini(body, context, chatHistory, threadInfo = {}) {
  try {
    const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` });
    const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]);
    const memberNames = threadInfo.userInfo?.map(u => ({ id: u.id, name: u.name, nickname: threadInfo.nicknames?.[u.id] })) || [];
    const prompt = `
      Phân tích ý định và trích xuất tham số từ câu lệnh sau: "${body}"
      Lịch sử trò chuyện: ${chatHistory.slice(-3).map(m => `${m.role}: ${m.content}`).join('\n')}
      Ngữ cảnh trước: ${context.lastIntent || 'casual'}, tin nhắn bot trước: ${context.lastBotMessage || 'Chưa có'}
      Danh sách thành viên nhóm: ${JSON.stringify(memberNames)}
      Các ý định có thể: nickname, groupImage, kick, add, groupName, poll, theme, emoji, action, menu, helpRequest, casual
      Trả về JSON với định dạng:
      {
        "intent": "tên ý định",
        "entities": { "tham số": "giá trị" },
        "confidence": 0.0 đến 1.0
      }
      Lưu ý:
      - Nếu ý định là "nickname", tìm tên người trong danh sách thành viên khớp nhất với entities.user.
      - Ví dụ: "!dun đổi biệt danh Gia Khang thành Mèo" → { "intent": "nickname", "entities": { "user": "Gia Khang", "nickname": "Mèo" }, "confidence": 0.95 }
    `;
    const { data } = await genaiService.models.generateContent({
      model: 'models/gemini-1.5-pro-latest',
      requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 200, temperature: 0.5 } },
      auth,
    });
    const result = JSON.parse(data?.candidates?.[0]?.content?.parts?.[0]?.text || '{}');
    return result.intent && result.entities ? result : { intent: 'casual', entities: {}, confidence: 0 };
  } catch (e) {
    console.error(`Error analyzing intent with Gemini:`, e.stack);
    return { intent: 'casual', entities: {}, confidence: 0 };
  }
}

function normalizeText(text) {
  return text.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
}

function cleanText(text) {
  return text
    .replace(/[^\p{L}\p{N}\s@:/.-😀-🙏]/gu, '')
    .replace(/(?<!\w)[!?.](?!\w)/g, '')
    .trim();
}

async function detectIntent(body, context = {}, chatHistory = [], api, threadID) {
  const intents = [
    { name: 'nickname', description: 'Đổi biệt danh thành viên', entities: ['user', 'nickname'], confirm: false, weight: 3 },
    { name: 'groupImage', description: 'Đổi ảnh nhóm', entities: ['url'], confirm: false, weight: 3 },
    { name: 'kick', description: 'Kick thành viên', entities: ['user'], confirm: true, weight: 2 },
    { name: 'add', description: 'Thêm thành viên', entities: ['user'], confirm: false, weight: 2 },
    { name: 'groupName', description: 'Đổi tên nhóm', entities: ['name'], confirm: false, weight: 3 },
    { name: 'poll', description: 'Tạo bình chọn', entities: ['options'], confirm: false, weight: 2 },
    { name: 'theme', description: 'Đổi chủ đề nhóm', entities: ['theme'], confirm: false, weight: 2 },
    { name: 'emoji', description: 'Đổi emoji nhóm', entities: ['emoji'], confirm: false, weight: 2 },
    { name: 'action', description: 'Tìm/phát nhạc', entities: ['query'], confirm: false, weight: 2 },
    { name: 'menu', description: 'Xem danh sách lệnh', entities: [], confirm: false, weight: 1 },
    { name: 'helpRequest', description: 'Yêu cầu trợ giúp', entities: [], confirm: false, weight: 1 },
    { name: 'casual', description: 'Trò chuyện thông thường', entities: [], confirm: false, weight: 0 },
  ];

  try {
    const threadInfo = await api.getThreadInfo(threadID).catch(e => {
      console.error(`Error fetching thread info ${threadID}:`, e.stack);
      return {};
    });

    const geminiResult = await analyzeIntentWithGemini(body, context, chatHistory, threadInfo);
    console.log('Gemini intent analysis:', geminiResult);

    const intentConfig = intents.find(i => i.name === geminiResult.intent) || intents.find(i => i.name === 'casual');
    
    const isValid = !intentConfig.entities.length || intentConfig.entities.every(ent => geminiResult.entities[ent]);
    if (!isValid) {
      console.log('Invalid entities for intent:', geminiResult.intent, geminiResult.entities);
      return { name: 'casual', matches: {}, score: 0, confidence: 0, confirm: false };
    }

    return {
      name: geminiResult.intent,
      matches: geminiResult.entities,
      score: geminiResult.confidence * 10,
      confidence: geminiResult.confidence,
      confirm: intentConfig.confirm || false,
    };
  } catch (e) {
    console.error('Error detecting intent:', e.stack);
    return { name: 'casual', matches: {}, score: 0, confidence: 0, confirm: false };
  }
}

async function processIntent(uid, body, event, api, intent, context, chatHistory) {
  const locks = new Map();
  while (locks.has(uid)) await new Promise(r => setTimeout(r, 10));
  locks.set(uid, true);

  try {
    globalThis.client.pendingCommands = globalThis.client.pendingCommands || new Map();
    const pending = globalThis.client.pendingCommands.get(uid);

    if (pending?.waitingFor === 'confirmKick' && body.toLowerCase() === 'ok') {
      globalThis.client.pendingCommands.delete(uid);
      const message = await executeGroupAction(api, event.threadID, 'kick', pending.userID);
      await updateContext(uid, body, message, 'kick', message);
      return { message };
    }

    if (pending?.waitingFor === 'singSelect' && body.match(/^[1-3]$/)) {
      const choice = parseInt(body) - 1;
      const { songs } = pending.data;
      globalThis.client.pendingCommands.delete(uid);
      if (!songs[choice]) return { message: `Số ${body} không hợp lệ! 😕` };
      const result = await downloadYouTubeAudio(songs[choice].url);
      if (result.error) return { message: result.error };
      const message = `Nhạc "${songs[choice].title}" đây! 🎵 ${result.fromCache ? '(cache)' : ''}`;
      await updateContext(uid, body, message, 'action', message);
      return { message, attachments: [fs.createReadStream(result.filePath), ...(Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [])].filter(Boolean) };
    }

    if (pending?.waitingFor) {
      globalThis.client.pendingCommands.delete(uid);
      return { message: 'Hủy lệnh! 😎' };
    }

    const groupActions = {
      nickname: {
        pattern: 'nickname',
        value: async () => {
          if (!intent.matches?.user || !intent.matches?.nickname) {
            return { error: 'Cần tên người và biệt danh mới (VD: đổi biệt danh Gia Khang thành Mèo)! 😝' };
          }
          const userID = await resolveUserID(api, event.threadID, intent.matches.user, event);
          return userID.error ? userID : [userID, intent.matches.nickname];
        },
        check: v => Array.isArray(v) && v[0] && v[1],
      },
      groupImage: {
        pattern: 'image',
        value: () => intent.matches?.url || { error: 'Cần link ảnh trực tiếp! 😝' },
      },
      kick: {
        pattern: 'kick',
        value: async () => intent.matches?.user ? await resolveUserID(api, event.threadID, intent.matches.user, event) : { error: 'Cần tên để kick! 😝' },
        confirm: true,
      },
      add: {
        pattern: 'add',
        value: async () => intent.matches?.user ? await resolveUserID(api, event.threadID, intent.matches.user, event) : { error: 'Cần tên để thêm! 😝' },
      },
      groupName: {
        pattern: 'name',
        value: () => intent.matches?.name || { error: 'Cần tên nhóm mới! 😝' },
      },
      poll: {
        pattern: 'poll',
        value: () => intent.matches?.options?.options?.length >= 2 ? intent.matches.options : { error: 'Cần câu hỏi và ít nhất 2 tùy chọn! 😝' },
        check: v => v?.options?.length >= 2,
      },
      theme: {
        pattern: 'theme',
        value: async () => intent.matches?.theme?.match(/^(blue|red|green|purple|pink)$/i) || await suggestThemeOrEmoji(intent.matches?.theme || 'default', 'theme'),
      },
      emoji: {
        pattern: 'emoji',
        value: async () => intent.matches?.emoji?.match(/[\u{1F600}-\u{1F64F}]/u) || await suggestThemeOrEmoji(intent.matches?.emoji || 'happy', 'emoji'),
      },
    };

    if (intent.name in groupActions) {
      if (!(await checkAdminPermission(uid, event.threadID, api))) return { message: 'Cần quyền admin! 😎' };
      const { pattern, value, check, confirm } = groupActions[intent.name];
      const val = await value();
      if (val?.error) return { message: val.error };
      if (check && !check(val)) return { message: 'Dữ liệu không hợp lệ! 😝' };
      if (confirm && intent.confirm) {
        globalThis.client.pendingCommands.set(uid, {
          command: intent.name,
          userID: val,
          user: intent.matches.user?.replace(/^@/, '') || val,
          waitingFor: 'confirmKick',
          timestamp: Date.now(),
        });
        return { message: `Chắc chắn muốn kick ${intent.matches.user?.replace(/^@/, '') || val}? Reply 'ok'! 😈` };
      }
      const message = await executeGroupAction(api, event.threadID, pattern, val);
      await updateContext(uid, body, message, intent.name, message);
      return { message };
    }

    if (intent.name === 'action') {
      const query = intent.matches?.query || body.replace(/\b(tìm|phát|mở|tải)\b.*\b(nhạc|bài hát|song)\b/i, '').trim();
      if (query.includes('youtube.com')) {
        const result = await downloadYouTubeAudio(query);
        if (result.error) return { message: result.error };
        const message = `Nhạc đây! 🎵 ${result.fromCache ? '(cache)' : ''}`;
        await updateContext(uid, body, message, 'action', message);
        return { message, attachments: [fs.createReadStream(result.filePath), ...(Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [])].filter(Boolean) };
      }
      const songs = await searchSong(query);
      if (!songs.length) return { message: `Không tìm thấy "${query}"! 😕` };
      globalThis.client.pendingCommands.set(uid, { command: 'sing', waitingFor: 'singSelect', data: { songs }, timestamp: Date.now() });
      const message = `Chọn bài:\n${songs.map((s, i) => `${i + 1}. ${s.title}`).join('\n')}\nReply số 1-3!`;
      await updateContext(uid, body, message, 'action', message);
      return { message };
    }

    if (intent.name === 'menu') {
      const commands = await caches.commands.get('commands')?.commands || await FileHandler.loadCommands();
      const message = `Danh sách lệnh:\n${commands.map(c => `🔹 ${c.name}: ${c.description}\nCách dùng: ${c.usages || c.name}`).join('\n')}`;
      await updateContext(uid, body, message, 'menu', message);
      return { message };
    }

    if (intent.name === 'helpRequest') {
      const message = `Khó xài? Gõ "!dun menu" để xem lệnh! 😎`;
      await updateContext(uid, body, message, 'helpRequest', message);
      return { message };
    }

    if (intent.name === 'casual') {
      const commands = await caches.commands.get('commands')?.commands || await FileHandler.loadCommands();
      const args = normalizeText(body).split(/\s+/).filter(Boolean);
      const cmdName = args[0].match(/^[!\/\#]?dun$/) && args[1] ? args[1] : '';
      const cmd = commands.find(c => normalizeText(c.name) === cmdName);
      if (cmd && await checkAdminPermission(uid, event.threadID, api)) {
        await cmd.module.onRun({ api, event, args: args.slice(2) });
        await updateContext(uid, body, 'Thực thi lệnh tùy chỉnh', 'command', 'Đã chạy lệnh!');
        return null;
      }
    }

    return null;
  } catch (e) {
    console.error(`Error processing intent for ${uid}:`, e.stack);
    return { message: `Lỗi xử lý lệnh: ${e.message}! 😭` };
  } finally {
    locks.delete(uid);
  }
}

async function handleGeminiResponse(uid, body, event, api, intent, chatHistory, context, retries = 0) {
  try {
    const intentResult = await processIntent(uid, body, event, api, intent, context, chatHistory);
    if (intentResult) return intentResult;

    const cacheKey = `${uid}:${body}`;
    if (caches.gemini.has(cacheKey) && Date.now() - caches.gemini.get(cacheKey).timestamp < CONFIG.cacheDuration) {
      const response = caches.gemini.get(cacheKey).response;
      await updateContext(uid, body, response, 'casual', response);
      return { message: response, attachments: Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [] };
    }

    const genaiService = await google.discoverAPI({ url: `https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta&key=${API_KEYS[currentApiKeyIndex]}` });
    const auth = new google.auth.GoogleAuth().fromAPIKey(API_KEYS[currentApiKeyIndex]);
    const prompt = `Bot vui tính, trả lời ngắn gọn, lầy lội kiểu Việt Nam.\nLịch sử:\n${chatHistory.slice(-3).map(m => `${m.role}: ${m.content}`).join('\n')}\nTin trước: ${context[uid]?.lastBotMessage || 'Chưa có'}\nDanh sách lệnh:\n${(await caches.commands.get('commands')?.commands || await FileHandler.loadCommands()).map(c => `${c.name}: ${c.description}`).join('\n')}\nCâu hỏi: "${body}"`;
    const { data } = await genaiService.models.generateContent({
      model: 'models/gemini-1.5-pro-latest',
      requestBody: { contents: [{ role: 'user', parts: [{ text: prompt }] }], generation_config: { maxOutputTokens: 2048, temperature: 0.7 } },
      auth,
    });
    const response = data?.candidates?.[0]?.content?.parts?.[0]?.text || 'Lỗi rồi, thử lại! 😅';
    await appendToChatHistory(uid, [...chatHistory, { role: 'user', content: body }, { role: 'assistant', content: response }]);
    caches.gemini.set(cacheKey, { response, timestamp: Date.now() });
    await updateContext(uid, body, response, 'casual', response);
    return { message: response, attachments: Math.random() < CONFIG.imageChance ? [await getRandomImage()] : [] };
  } catch (e) {
    console.error(`Error in Gemini response for ${uid}:`, e.stack);
    if (e.response?.status === 429 && retries < 3 && currentApiKeyIndex < API_KEYS.length - 1) {
      currentApiKeyIndex++;
      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, retries)));
      return handleGeminiResponse(uid, body, event, api, intent, chatHistory, context, retries + 1);
    }
    return { message: `Lỗi Gemini: ${e.message}! Thử lại nhé! 😭` };
  }
}

export default {
  config: {
    name: 'dun',
    author: 'Trần Thanh Dương',
    version: '1.0.0',
    role: 0,
    group: 'Tiện ích',
    description: '',
    usages: '',
    usePrefix: true,
    delay: 0,
    subcommands: {
      history: {
        role: 0,
        delay: 5,
        onRun: async ({ api, event, args }) => {}
      },
      cache: {
        role: 0,
        delay: 5,
        onRun: async ({ api, event, args }) => {}
      }
    }
  },
  initialize() {
    try {
      FileHandler.ensureDir(CONFIG.cacheDir);
      FileHandler.loadCommands();
    } catch (e) {
      console.error('Error initializing bot:', e.stack);
    }
  },
  async onRun({ api, event }) {
    try {
      this.initialize();
      const uid = event.senderID;
      const body = event.body?.trim();
      if (!body) return api.sendMessage('Nói gì đi, tui chờ! 😝', event.threadID);
      const context = FileHandler.loadJSON(CONFIG.contextPath);
      const chatHistory = loadChatHistory(uid);
      const intent = await detectIntent(body, context[uid], chatHistory, api, event.threadID);
      const response = await handleGeminiResponse(uid, body, event, api, intent, chatHistory, context);
      if (!response) return;
      api.sendMessage({ body: response.message, attachment: response.attachments }, event.threadID, (err, info) => {
        if (err) {
          console.error(err);
          return;
        }
        globalThis.client.handleReply.push({ type: 'reply', name: this.config.name, messageID: info.messageID, author: uid });
        if (Math.random() < 0.3) api.setMessageReaction(CONFIG.reactions[Math.floor(Math.random() * CONFIG.reactions.length)], info.messageID);
      });
    } catch (e) {
      console.error(e);
      api.sendMessage(`Lỗi bot: ${e.message}! Thử lại nhé! 😭`, event.threadID);
    }
  },
  async onReply({ api, event }) {
    try {
      this.initialize();
      const { threadID, messageID, senderID, body } = event;
      const context = FileHandler.loadJSON(CONFIG.contextPath);
      const chatHistory = loadChatHistory(senderID);
      const intent = await detectIntent(body || '', context[senderID], chatHistory, api, threadID);
      const response = await handleGeminiResponse(senderID, body?.trim() || '', event, api, intent, chatHistory, context);
      if (!response) return;
      api.sendMessage({ body: response.message, attachment: response.attachments }, threadID, (err, info) => {
        if (err) {
          console.error(err);
          return;
        }
        globalThis.client.handleReply.push({ type: 'reply', name: this.config.name, messageID: info.messageID, author: senderID });
        if (Math.random() < 0.3) api.setMessageReaction(CONFIG.reactions[Math.floor(Math.random() * CONFIG.reactions.length)], info.messageID);
      }, messageID);
    } catch (e) {
      console.error(e);
      api.sendMessage(`Lỗi xử lý reply: ${e.message}! Thử lại nhé! 😭`, event.threadID);
    }
  },
};