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
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
/**
 * ═══════════════════════════════════════════════════════════════════════
 * HANDLER: Sticker + View-Once Commands
 * ═══════════════════════════════════════════════════════════════════════
 * 🎨 Comandos de sticker com metadados personalizados
 * πŸ‘οΈ  Comandos para revelar e converter view-once
 * ═══════════════════════════════════════════════════════════════════════
 */

const MediaProcessor = require('./MediaProcessor');
const { getContentType } = require('@whiskeysockets/baileys');

class StickerViewOnceHandler {
  constructor(sock, config) {
    this.sock = sock;
    this.config = config;
    this.media = new MediaProcessor();
  }

  /**
   * Processa comando #sticker / #s / #fig
   * Cria sticker a partir de imagem ou sticker existente
   */
  async handleSticker(m, userData, texto, ehGrupo) {
    try {
      const { nome: userName } = userData;
      
      // Procura mensagem citada
      let quoted = m.message?.extendedTextMessage?.contextInfo?.quotedMessage;
      if (quoted?.viewOnceMessageV2?.message) quoted = quoted.viewOnceMessageV2.message;
      else if (quoted?.viewOnceMessageV2Extension?.message) quoted = quoted.viewOnceMessageV2Extension.message;
      else if (quoted?.viewOnceMessage?.message) quoted = quoted.viewOnceMessage.message;

      const hasImage = m.message?.imageMessage || quoted?.imageMessage;
      const hasSticker = quoted?.stickerMessage;

      if (!hasImage && !hasSticker) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: 'πŸ“Έ *COMANDO #sticker*\n\n' +
                'βœ… Envie uma imagem com legenda `#sticker`\n' +
                'βœ… OU responda uma imagem com `#sticker`\n' +
                'βœ… OU responda um sticker com `#sticker`\n\n' +
                '⚠️ Para stickers animados de vídeos, use `#gif`\n\n' +
                'πŸ“ Metadados:\n' +
                '🏷️ Pack: akira-bot-[seu_nome]\n' +
                'πŸ‘€ Autor: akira-bot\n' +
                '✨ Automaticamente personalizados!'
        }, { quoted: m });
        return true;
      }

      // Processa sticker de sticker
      if (hasSticker) {
        const stickerMsg = quoted.stickerMessage;
        const stickerBuf = await this.media.downloadMedia(stickerMsg, 'sticker');

        if (!stickerBuf) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao baixar sticker.'
          }, { quoted: m });
          return true;
        }

        const out = await this.media.addStickerMetadata(
          stickerBuf,
          `akira-bot-${userName.split(' ')[0].toLowerCase()}`,
          'akira-bot'
        );

        if (!out) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao personalizar sticker.'
          }, { quoted: m });
          return true;
        }

        await this.sock.sendMessage(m.key.remoteJid, {
          sticker: out
        }, { quoted: m });

        return true;
      }

      // Processa imagem β†’ sticker
      if (hasImage) {
        const mediaMsg = quoted?.imageMessage || m.message.imageMessage;
        const imgBuf = await this.media.downloadMedia(mediaMsg, 'image');

        if (!imgBuf) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao baixar imagem.'
          }, { quoted: m });
          return true;
        }

        const result = await this.media.createStickerFromImage(imgBuf, {
          userName,
          author: 'akira-bot'
        });

        if (!result.sucesso) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: `❌ ${result.error}`
          }, { quoted: m });
          return true;
        }

        await this.sock.sendMessage(m.key.remoteJid, {
          sticker: result.buffer
        }, { quoted: m });

        return true;
      }

    } catch (e) {
      console.error('❌ Erro em handleSticker:', e);
      await this.sock.sendMessage(m.key.remoteJid, {
        text: '❌ Erro ao processar sticker.'
      }, { quoted: m });
    }

    return true;
  }

  /**
   * Processa comando #gif
   * Cria sticker animado de vΓ­deo
   */
  async handleGif(m, userData, texto, ehGrupo) {
    try {
      const { nome: userName } = userData;

      let quoted = m.message?.extendedTextMessage?.contextInfo?.quotedMessage;
      if (quoted?.viewOnceMessageV2?.message) quoted = quoted.viewOnceMessageV2.message;
      else if (quoted?.viewOnceMessageV2Extension?.message) quoted = quoted.viewOnceMessageV2Extension.message;
      else if (quoted?.viewOnceMessage?.message) quoted = quoted.viewOnceMessage.message;

      const hasVideo = m.message?.videoMessage || quoted?.videoMessage;
      const hasSticker = quoted?.stickerMessage;

      if (!hasVideo && !hasSticker) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: 'πŸŽ₯ *COMANDO #gif*\n\n' +
                'βœ… Envie um vΓ­deo com legenda `#gif`\n' +
                'βœ… OU responda um vΓ­deo com `#gif`\n' +
                'βœ… OU responda um sticker animado com `#gif`\n\n' +
                '⏱️ MÑximo: 30 segundos\n' +
                'πŸ“ DimensΓ£o: 512x512 (automΓ‘tico)\n' +
                'πŸ’Ύ MΓ‘ximo: 500KB\n\n' +
                '✨ Seu sticker serÑ automaticamente personalizado!'
        }, { quoted: m });
        return true;
      }

      // Processa sticker animado existente
      if (hasSticker) {
        const stickerMsg = quoted.stickerMessage;
        const stickerBuf = await this.media.downloadMedia(stickerMsg, 'sticker');

        if (!stickerBuf) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao baixar sticker.'
          }, { quoted: m });
          return true;
        }

        // Tenta apenas re-injetar metadados
        const out = await this.media.addStickerMetadata(
          stickerBuf,
          `akira-bot-${userName.split(' ')[0].toLowerCase()}`,
          'akira-bot'
        );

        if (out) {
          await this.sock.sendMessage(m.key.remoteJid, {
            sticker: out
          }, { quoted: m });
        } else {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao personalizar sticker animado.'
          }, { quoted: m });
        }

        return true;
      }

      // Processa vΓ­deo β†’ sticker animado
      if (hasVideo) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: '⏳ Processando vídeo... Isto pode levar alguns segundos.'
        }, { quoted: m });

        const vidMsg = quoted?.videoMessage || m.message.videoMessage;
        const vidBuf = await this.media.downloadMedia(vidMsg, 'video');

        if (!vidBuf) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: '❌ Erro ao baixar vídeo.'
          }, { quoted: m });
          return true;
        }

        const result = await this.media.createAnimatedStickerFromVideo(vidBuf, 30, {
          userName,
          author: 'akira-bot'
        });

        if (!result.sucesso) {
          await this.sock.sendMessage(m.key.remoteJid, {
            text: `❌ ${result.error}`
          }, { quoted: m });
          return true;
        }

        await this.sock.sendMessage(m.key.remoteJid, {
          sticker: result.buffer
        }, { quoted: m });

        return true;
      }

    } catch (e) {
      console.error('❌ Erro em handleGif:', e);
      await this.sock.sendMessage(m.key.remoteJid, {
        text: '❌ Erro ao criar sticker animado.'
      }, { quoted: m });
    }

    return true;
  }

  /**
   * Processa comando #reveal / #revelar / #openvo
   * Revela view-once (apenas dono/admin)
   */
  async handleReveal(m, userData, ehGrupo, isOwnerOrAdmin) {
    try {
      if (!isOwnerOrAdmin) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: '🚫 Comando restrito ao dono ou admin do grupo.'
        }, { quoted: m });
        return true;
      }

      const quoted = m.message?.extendedTextMessage?.contextInfo?.quotedMessage;

      if (!quoted) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: 'πŸ‘οΈ *COMANDO #reveal*\n\n' +
                'Responda uma mensagem view-once com `#reveal`\n\n' +
                'βœ… Imagens view-once\n' +
                'βœ… VΓ­deos view-once\n' +
                'βœ… Áudios view-once\n' +
                'βœ… Stickers animados view-once\n\n' +
                'πŸ”’ Apenas dono/admin podem usar.'
        }, { quoted: m });
        return true;
      }

      // Extrai conteΓΊdo view-once
      const result = await this.media.extractViewOnceContent(quoted);

      if (!result.sucesso) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: `❌ ${result.error}`
        }, { quoted: m });
        return true;
      }

      // Envia conteΓΊdo revelado
      const tipoEmoji = {
        'image': 'πŸ–ΌοΈ',
        'video': '🎬',
        'audio': '🎀',
        'sticker': '🎨'
      };

      const caption = `${tipoEmoji[result.tipo] || 'πŸ“¦'} *ConteΓΊdo Revelado (View-Once)*\n\nTipo: ${result.tipo}\nTamanho: ${(result.size / 1024).toFixed(2)}KB`;

      const msgObj = {};
      if (result.tipo === 'image') {
        msgObj.image = result.buffer;
        msgObj.caption = caption;
      } else if (result.tipo === 'video') {
        msgObj.video = result.buffer;
        msgObj.mimetype = 'video/mp4';
        msgObj.caption = caption;
      } else if (result.tipo === 'audio') {
        msgObj.audio = result.buffer;
        msgObj.mimetype = 'audio/mpeg';
        msgObj.ptt = false;
      } else if (result.tipo === 'sticker') {
        msgObj.sticker = result.buffer;
      }

      await this.sock.sendMessage(m.key.remoteJid, msgObj, { quoted: m });
      return true;

    } catch (e) {
      console.error('❌ Erro em handleReveal:', e);
      await this.sock.sendMessage(m.key.remoteJid, {
        text: '❌ Erro ao revelar view-once.'
      }, { quoted: m });
    }

    return true;
  }

  /**
   * Processa comando #toimg
   * Converte sticker para imagem PNG
   */
  async handleToImage(m, userData, texto, ehGrupo) {
    try {
      let quoted = m.message?.extendedTextMessage?.contextInfo?.quotedMessage;
      if (quoted?.viewOnceMessageV2?.message) quoted = quoted.viewOnceMessageV2.message;
      else if (quoted?.viewOnceMessageV2Extension?.message) quoted = quoted.viewOnceMessageV2Extension.message;
      else if (quoted?.viewOnceMessage?.message) quoted = quoted.viewOnceMessage.message;

      const hasSticker = m.message?.stickerMessage || quoted?.stickerMessage;

      if (!hasSticker) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: 'πŸ–ΌοΈ *COMANDO #toimg*\n\n' +
                'βœ… Envie um sticker com legenda `#toimg`\n' +
                'βœ… OU responda um sticker com `#toimg`\n\n' +
                'πŸ“ Converte qualquer sticker para imagem PNG\n' +
                '⚠️ Stickers animados não podem ser convertidos para imagem estÑtica'
        }, { quoted: m });
        return true;
      }

      await this.sock.sendMessage(m.key.remoteJid, {
        text: '⏳ Convertendo sticker para imagem...'
      }, { quoted: m });

      const stickerMsg = quoted?.stickerMessage || m.message.stickerMessage;
      const stickerBuf = await this.media.downloadMedia(stickerMsg, 'sticker');

      if (!stickerBuf) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: '❌ Erro ao baixar sticker.'
        }, { quoted: m });
        return true;
      }

      // Converte WebP para PNG
      const result = await this.media.convertStickerToImage(stickerBuf);

      if (!result.sucesso) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: `❌ ${result.error || 'Erro ao converter sticker.'}`
        }, { quoted: m });
        return true;
      }

      await this.sock.sendMessage(m.key.remoteJid, {
        image: result.buffer,
        caption: 'πŸ–ΌοΈ Convertido de sticker para imagem PNG'
      }, { quoted: m });

      return true;

    } catch (e) {
      console.error('❌ Erro em handleToImage:', e);
      await this.sock.sendMessage(m.key.remoteJid, {
        text: '❌ Erro ao converter sticker para imagem.'
      }, { quoted: m });
    }

    return true;
  }

  /**
   * Processa comando #vosticker / #vostk
   * Converte view-once image/video em sticker
   */
  async handleViewOnceToSticker(m, userData, ehGrupo) {
    try {
      const { nome: userName } = userData;
      const quoted = m.message?.extendedTextMessage?.contextInfo?.quotedMessage;

      if (!quoted) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: 'πŸ‘οΈβž‘οΈπŸŽ¨ *COMANDO #vosticker*\n\n' +
                'Converte imagem/vΓ­deo view-once em sticker\n\n' +
                'Uso: Responda uma imagem/vΓ­deo view-once com `#vosticker`\n\n' +
                'βœ… View-once image β†’ sticker\n' +
                'βœ… View-once video β†’ sticker animado (atΓ© 30s)\n' +
                'βœ… Metadados: akira-bot-[seu_nome]'
        }, { quoted: m });
        return true;
      }

      const result = await this.media.extractViewOnceContent(quoted);

      if (!result.sucesso) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: `❌ ${result.error}`
        }, { quoted: m });
        return true;
      }

      let stickerResult;

      if (result.tipo === 'image') {
        stickerResult = await this.media.createStickerFromImage(result.buffer, {
          userName,
          author: 'akira-bot'
        });
      } else if (result.tipo === 'video') {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: '⏳ Convertendo vídeo view-once para sticker animado...'
        }, { quoted: m });

        stickerResult = await this.media.createAnimatedStickerFromVideo(result.buffer, 30, {
          userName,
          author: 'akira-bot'
        });
      } else {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: `❌ Tipo ${result.tipo} não pode ser convertido para sticker.`
        }, { quoted: m });
        return true;
      }

      if (!stickerResult.sucesso) {
        await this.sock.sendMessage(m.key.remoteJid, {
          text: `❌ ${stickerResult.error}`
        }, { quoted: m });
        return true;
      }

      await this.sock.sendMessage(m.key.remoteJid, {
        sticker: stickerResult.buffer
      }, { quoted: m });

      return true;

    } catch (e) {
      console.error('❌ Erro em handleViewOnceToSticker:', e);
      await this.sock.sendMessage(m.key.remoteJid, {
        text: '❌ Erro ao converter view-once para sticker.'
      }, { quoted: m });
    }

    return true;
  }
}

module.exports = StickerViewOnceHandler;