const { getCurrentTrack, getPlayer } = require('../utils/queueManager');
const { EmbedBuilder } = require('discord.js');
const fs = require('fs');
const { execSync } = require('child_process');

module.exports = {
    name: 'np',
    description: 'Show the currently playing track and time left',
    async execute(message) {
        const currentTrack = getCurrentTrack(message.guild.id);

        if (!currentTrack) {
            return message.reply('There is no track currently playing.');
        }

        const player = getPlayer(message.guild.id);
        if (!player) {
            return message.reply('There is no track currently playing.');
        }

        if (!fs.existsSync(currentTrack.filePath)) {
            console.error('Current track file not found:', currentTrack.filePath);
            return message.reply('The current track file is missing.');
        }

        const currentTime = player.state?.resource?.playbackDuration || 0;
        const totalDuration = await getTrackDuration(currentTrack.filePath);
        const timeLeft = msToTime(totalDuration - currentTime);

        const embed = new EmbedBuilder()
            .setColor('#0099ff')
            .setTitle('Now Playing')
            .setDescription(`**${currentTrack.title}**`)
            .setThumbnail(currentTrack.thumbnailUrl || message.guild.iconURL())
            .addFields(
                { name: 'Time Left', value: timeLeft },
            )
            .setFooter({ text: `Requested by ${currentTrack.requester}`, iconURL: currentTrack.avatarURL })
            .setTimestamp();

        message.channel.send({ embeds: [embed] });
    },
};

function msToTime(duration) {
    let seconds = Math.floor((duration / 1000) % 60),
        minutes = Math.floor((duration / (1000 * 60)) % 60),
        hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    hours = (hours < 10) ? "0" + hours : hours;
    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;

    return hours + ":" + minutes + ":" + seconds;
}

async function getTrackDuration(filePath) {
    try {
        const output = execSync(`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${filePath}"`).toString().trim();
        return parseFloat(output) * 1000;
    } catch (error) {
        console.error('Error getting track duration:', error);
        return 0;
    }
}