const { default: axios } = require("axios");

module.exports = class {
    static config = {
        name: 'autodown',
        aliases: ["autodown"],
        version: '1.1.1',
        role: 2,
        author: 'DongDev',
        info: 'Tự động tải xuống khi phát hiện liên kết',
        Category: 'Tiện ích',
        guides: '[]',
        cd: 2,
        hasPrefix: true,
        images: []
    };

    static urlify(text) {
        const urlRegex = /(https?:\/\/[^\s]+)/gi;
        const matches = text.match(urlRegex);
        return matches || [];
    }

    static async onEvent({ api, event, msg }) {
        if (event.senderID == (global.botID || api.getCurrentUserID())) return;
        const send = (a, b, c, d) => api.sendMessage(a, b || event.threadID, c || null, d || event.messageID);
        const head = app => `[ AUTODOWN - ${app} ]\n────────────────`;
        const urls = this.urlify(event.body);
        
        for (const str of urls) {
            if (/^https?:\/\/(?:vm\.|vt\.|v\.|www\.)?(?:tiktok)\.com\//.test(str)) {
                const res = await global.api.tiktok.downloadv3(str);
                if (res.attachments && res.attachments.length > 0) {
                    let attachment = [];
                    for (const attachmentItem of res.attachments) {
                        if (attachmentItem.type === 'Video') {
                            attachment.push(await global.tools.streamURL(attachmentItem.url, 'mp4'));
                        } else if (attachmentItem.type === 'Photo') {
                            attachment.push(await global.tools.streamURL(attachmentItem.url, 'jpg'));
                        }
                    }
                    msg.reply({
                        body: `${head('TIKTOK')}\n⩺ Tiêu đề: ${res.message || ""}\n⩺ Lượt xem: ${res.stats.views}\n⩺ Lượt thích: ${res.stats.likes}\n⩺ Bình luận: ${res.stats.comments}\n⩺ Chia sẻ: ${res.stats.shares}\n⩺ Lượt lưu: ${res.stats.collects}\n⩺ Tác giả: ${res.author.name} (${res.author.username})\n⩺ Âm nhạc: ${res.music.title}\n⩺ Thời lượng: ${res.music.duration} giây\n⩺ Thả cảm xúc '😆' để tải nhạc`,
                        attachment
                    }, (err, dataMsg) => {
                        global.Seiko.onReaction.push({
                            name: this.config.name,
                            messageID: dataMsg.messageID,
                            title: res.music.title || "",
                            author: res.music.author,
                            url: res.music.url,
                            type: "TIKTOK"
                        });
                    });
                }
            } else if (/facebook\.com|fb\.watch/.test(str)) {
                const res = await global.api.facebook(encodeURIComponent(str));
                if (res.attachments && res.attachments.length > 0) {
                    let attachment = [];
                    if (res.queryStorieID) {
                        const match = res.attachments.find(item => item.id == res.queryStorieID);
                        if (match && match.type === 'Video') {
                            const videoUrl = match.url.hd || match.url.sd;
                            attachment.push(await global.tools.streamURL(videoUrl, 'mp4'));
                        } else if (match && match.type === 'Photo') {
                            attachment.push(await global.tools.streamURL(match.url, 'jpg'));
                        }
                    } else {
                        for (const attachmentItem of res.attachments) {
                            if (attachmentItem.type === 'Video') {
                                const videoUrl = attachmentItem.url.hd || attachmentItem.url.sd;
                                attachment.push(await global.tools.streamURL(videoUrl, 'mp4'));
                            } else if (attachmentItem.type === 'Photo') {
                                attachment.push(await global.tools.streamURL(attachmentItem.url, 'jpg'));
                            }
                        }
                    }
                    msg.reply({
                        body: `${head('FACEBOOK')}\n⩺ Tiêu đề: ${res.message || "null"}${res.like ? `\n⩺ Lượt thích: ${res.like}` : ''}${res.comment ? `\n⩺ Bình luận: ${res.comment}` : ''}${res.share ? `\n⩺ Chia sẻ: ${res.share}` : ''}\n⩺ Tác giả: ${res.author || "unknown"}`,
                        attachment
                    });
                }
            } else if (/youtube|youtu/.test(str)) {
                const res = await global.api.youtube.downloadv1(str);
                msg.reply({
                    body: `${head('YOUTUBE')}\n⩺ Title: ${res.title}\n⩺ Thời lượng: ${res.duration}`,
                    attachment: await global.tools.streamURL(res.url, 'mp4')
                });
            } else if (/instagram/.test(str)) {
                const res = await global.api.instagram.download(str);
                let attachments = [];
                if (res.attachments && res.attachments.length > 0) {
                    for (const at of res.attachments) {
                        if (at.type === 'Video') {
                            attachments.push(await global.tools.streamURL(at.url, 'mp4'));
                        } else if (at.type === 'Photo') {
                            attachments.push(await global.tools.streamURL(at.url, 'jpg'));
                        }
                    }
                    msg.reply({
                        body: `${head('INSTAGRAM')}\n⩺ Tiêu đề: ${res.message}\n⩺ Tác giả: ${res.author}\n⩺ Lượt thích: ${res.like}\n⩺ Bình luận: ${res.comment}`,
                        attachment: attachments
                    });
                }
            } else if (/capcut/.test(str)) {
                const chosenVideo = await global.api.capcut.downloadv2(str);
                send({
                    body: `${head('CAPCUT')}\n⩺ Tiêu đề: ${chosenVideo.short_title} ${chosenVideo.title}\n⩺ Tác giả: ${chosenVideo.author.name} (${chosenVideo.author.unique_id})\n⩺ Số ảnh cần dùng: ${chosenVideo.fragment_count}\n⩺ Lượt dùng mẫu: ${chosenVideo.usage_amount}\n⩺ Lượt xem: ${chosenVideo.play_amount}\n⩺ Lượt thích: ${chosenVideo.like_count}\n⩺ Bình luận: ${chosenVideo.comment_count}\n⩺ Lượt lưu: ${chosenVideo.favorite_count}`,
                    attachment: await global.tools.streamURL(chosenVideo.video_url, 'mp4')
                });
            } else if (/soundcloud/.test(str)) {
                const result = await global.api.scldlv2(str);
                send({
                    body: `${head('SOUNDCLOUD')}\n⩺ Tiêu đề: ${result.title}\n⩺ Tác giả: ${result.author.username}`,
                    attachment: await global.tools.streamURL(result.url, 'mp3')
                });
            } else if (/threads\.net\//.test(str)) {
                const res = await global.api.threads.downloadv1(str);
                const data = res.results;
                const videos = data.filter(item => item.type === 'video');
                const photos = data.filter(item => item.type === 'image');
                
                const sendMedia = async (attachment) => {
                    await send({
                        body: `${head('THREADS')}\n⩺ Tiêu đề: ${res.title}\n⩺ Tác giả: ${res.user.username}`,
                        attachment
                    });
                };

                if (videos.length > 0) {
                    const videoAttachments = await Promise.all(videos.map(item => global.tools.streamURL(item.url, 'mp4')));
                    const filteredVideos = videoAttachments.filter(item => !!item);
                    if (filteredVideos.length > 0) await sendMedia(filteredVideos);
                }

                if (photos.length > 0) {
                    const photoAttachments = await Promise.all(photos.map(item => global.tools.streamURL(item.url, 'jpg')));
                    const filteredPhotos = photoAttachments.filter(item => !!item);
                    if (filteredPhotos.length > 0) await sendMedia(filteredPhotos);
                }
            } else if (/douyin/.test(str)) {
                const res = await global.api.downall.downloadv1(str);
                if (res.error) {
                    send({ body: `${head('DOUYIN')}\nCó lỗi khi tải dữ liệu: ${res.message}` });
                    return;
                }
                
                if (res.attachments && res.attachments.length > 0) {
                    let attachment = [];
                    for (const media of res.attachments) {
                        const stream = await global.tools.streamURL(media.url, media.extension || 'mp4');
                        if (stream) attachment.push(stream);
                    }
                    
                    if (attachment.length > 0) {
                        await msg.reply({
                            body: `${head('DOUYIN')}\n⩺ Tiêu đề: ${res.title}${res.audio ? '\n⩺ Thả cảm xúc \'😆\' để tải nhạc' : ''}`,
                            attachment
                        }, (error, info) => {
                            if (res.audio) {
                                global.Seiko.onReaction.push({
                                    type: "DOUYIN",
                                    name: this.config.name,
                                    messageID: info.messageID,
                                    author: event.senderID,
                                    title: res.title,
                                    url: res.audio
                                });
                            }
                        });
                    }
                }
            } else if (/zingmp3/.test(str)) {
                const res = await global.api.zingmp3.downloadv1(str);
                if (res.error) {
                    send({ body: `${head('ZINGMP3')}\n⩺ Lỗi: ${res.message}` });
                    return;
                }
                
                const stream = await global.tools.streamURL(res.url, 'mp3');
                if (!stream) {
                    send({ body: `${head('ZINGMP3')}\n⩺ Lỗi: Không thể tải nhạc` });
                    return;
                }
                
                send({
                    body: `${head('ZINGMP3')}\n⩺ Tiêu đề: ${res.title}\n⩺ Ca sĩ: ${res.artist}\n⩺ Chất lượng: ${res.quality}`,
                    attachment: stream
                });
            } else if (/https?:\/\/(open\.)?spotify\.com\/(track|album|playlist|artist|show|episode)\/[a-zA-Z0-9]+/.test(str)) {
                try {
                    const res = await global.api.downall.downloadv1(str);
                    if (res.error) {
                        send({ body: `${head('SPOTIFY')}\nCó lỗi khi tải dữ liệu từ Spotify: ${res.message}` });
                        return;
                    }
                    
                    send({
                        body: `${head('SPOTIFY')}\n⩺ Title: ${res.title || 'Unknown'}\n⩺ Duration: ${res.duration || 'Unknown'}\n⩺ Artist: ${res.artist || 'Unknown'}`,
                        attachment: await global.tools.streamURL(res.medias[0].url, 'mp3')
                    });
                } catch (error) {
                    console.error("Error fetching data from Spotify:", error);
                    send({ body: `${head('SPOTIFY')}\nCó lỗi khi tải dữ liệu từ Spotify.` });
                }
            }
        }
    }

    static async onReaction({ api, event, onReaction, msg }) {
        const { type, url, title, author } = onReaction;
        if (type === "TIKTOK" || type === "DOUYIN" || type === "YOUTUBE") {
            msg.reply({
                body: `[ MUSIC ${type} ]\n────────────────\n⩺ Tiêu đề: ${title}`,
                attachment: await global.tools.streamURL(url, 'mp3')
            });
        }
    }

    static async onRun() {
        // Implementation for onRun if needed
    }
}