/**
 * RADIO BOT IRC - COOKIES ENABLED VERSION
 * Support: Cookies.txt untuk bypass limit YouTube
 */

const irc = require('irc-upd');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

// --- KONFIGURASI ---
const config = {
    server: "irc.ayochat.or.id",
    port: 6667,
    nick: "ayoradio",
    userName: "radio",
    realName: "ayoradio",
    channels: ["#ayochat", "#ayoradio"], 
    adminChannel: "#ayoradio", 
    
    // Shoutcast
    scHost: "45.77.254.153",
    scPort: "8000",
    scPass: "ayoradio",
    scUser: "source", 
    
    // Path File
    ytdlpPath: path.join(process.env.HOME, 'bin', 'yt-dlp'),
    ffmpegPath: path.join(process.env.HOME, 'bin', 'ffmpeg'),
    cookiesPath: path.join(__dirname, 'cookies.txt'), // Lokasi file cookies
    downloadDir: path.join(__dirname, 'downloads')
};

// Buat folder download
if (!fs.existsSync(config.downloadDir)) fs.mkdirSync(config.downloadDir);

// Cek apakah Cookies ada?
if (fs.existsSync(config.cookiesPath)) {
    console.log("✅ Cookies.txt ditemukan! Bot akan menggunakan cookies.");
} else {
    console.log("⚠️ Cookies.txt TIDAK ditemukan. Bot berjalan tanpa login (Rawan limit).");
}

// --- VARIABLE STATUS ---
let queue = [];
let isPlaying = false;
let isLiveDJ = false;
let currentDJ = null;
let currentProcess = null;

// --- ANTI CRASH ---
process.on('uncaughtException', (err) => console.error('⚠️ ERROR:', err));
process.on('unhandledRejection', (reason) => console.error('⚠️ REJECTION:', reason));

// --- KONEKSI IRC ---
const client = new irc.Client(config.server, config.nick, {
    channels: config.channels,
    userName: config.userName,
    realName: config.realName,
    autoRejoin: true,
    retryCount: 5,
});

client.addListener('error', (message) => console.log('IRC Error:', message.command));
client.addListener('registered', () => console.log('✅ Bot Online di IRC'));

// --- LISTENER PESAN ---
client.addListener('message', function (from, to, text) {
    if (from === config.nick) return;

    const args = text.trim().split(' ');
    const cmd = args[0].toLowerCase();
    const content = args.slice(1).join(' ');

    // !req
    if (cmd === '!req') {
        if (!content) return client.say(to, "Format: !req Judul Lagu");

        if (isLiveDJ) {
            if (currentDJ) {
                client.say(currentDJ, `📩 REQ dari ${from}: ${content}`);
                client.say(to, `Request dikirim ke DJ ${currentDJ}.`);
            } else {
                client.say(to, "Request dicatat (Mode DJ Aktif).");
            }
        } else {
            client.say(to, `🔍 Mencari: ${content}...`);
            searchAndQueue(from, content, to);
        }
    }

    // !pesan
    if (cmd === '!pesan') {
        if (isLiveDJ && currentDJ) {
            client.say(currentDJ, `📝 PESAN dari ${from}: ${content}`);
            client.say(to, "Pesan terkirim ke DJ.");
        } else {
            client.say(to, "Pesan salam dicatat.");
        }
    }

    // !list
    if (cmd === '!list') {
        if (isLiveDJ) return client.say(to, "🚫 Mode Live DJ sedang aktif.");
        if (queue.length === 0) return client.say(to, "Antrian kosong.");
        
        let msg = "Playlist: ";
        queue.slice(0, 3).forEach((s, i) => msg += `[${i+1}. ${s.title}] `);
        client.say(to, msg);
    }

    // !stream
    if (cmd === '!stream') {
        client.say(to, `📻 Link: http://${config.scHost}:${config.scPort}/stream`);
    }

    // --- FITUR ADMIN ---
    if (to.toLowerCase() === config.adminChannel.toLowerCase()) {
        if (cmd === '!dj' && args[1] === 'on') {
            isLiveDJ = true;
            currentDJ = from;
            stopStreaming(); 
            client.action(config.channels[0], `🎤 MODE LIVE DJ ON! Mic diserahkan ke ${from}`);
            client.say(to, "✅ AutoDJ Mati. Silakan siaran!");
        }

        if (cmd === '!dj' && args[1] === 'off') {
            isLiveDJ = false;
            currentDJ = null;
            client.action(config.channels[0], `🤖 MODE AUTO DJ ON. Silakan !req`);
            client.say(to, "✅ AutoDJ Hidup kembali...");
            checkQueue();
        }

        if (cmd === '!skip') {
            if (isLiveDJ) return client.say(to, "Gak bisa skip pas Live DJ.");
            if (currentProcess) {
                client.say(to, "⏭️ Skip...");
                stopStreaming();
            }
        }
    }
});

// --- ENGINE ---

function searchAndQueue(requester, query, channel) {
    // Siapkan argumen yt-dlp
    let ytArgs = [
        '--no-warnings', 
        '--default-search', 'ytsearch', 
        '--dump-json', 
        '--no-playlist', 
        '-n', '1'
    ];

    // Tambahkan cookies jika file ada
    if (fs.existsSync(config.cookiesPath)) {
        ytArgs.push('--cookies', config.cookiesPath);
    }

    ytArgs.push(query);

    const search = spawn(config.ytdlpPath, ytArgs);

    let rawData = '';
    search.stdout.on('data', (chunk) => { rawData += chunk; });
    
    search.on('close', (code) => {
        if (code === 0) {
            // Parsing baris per baris (Tahan Banting)
            const lines = rawData.toString().split('\n');
            let foundInfo = null;

            for (const line of lines) {
                if (line.trim().length === 0) continue;
                try {
                    const parsed = JSON.parse(line);
                    if (parsed.title && (parsed.url || parsed.webpage_url)) {
                        foundInfo = parsed;
                        break; 
                    }
                } catch (e) {}
            }

            if (foundInfo) {
                const song = {
                    title: foundInfo.title,
                    url: foundInfo.webpage_url || foundInfo.url,
                    id: foundInfo.id,
                    requester: requester
                };
                queue.push(song);
                client.say(channel, `✅ Antrian: ${song.title}`);
                
                if (!isPlaying && !isLiveDJ) checkQueue();
            } else {
                client.say(channel, "Lagu tidak ditemukan (Format data error).");
            }
        } else {
            client.say(channel, "Lagu tidak ditemukan.");
        }
    });
}

function checkQueue() {
    if (isLiveDJ) return;
    if (isPlaying) return;
    
    if (queue.length > 0) {
        const nextSong = queue.shift();
        playStream(nextSong);
    }
}

function stopStreaming() {
    if (currentProcess) {
        try { currentProcess.kill('SIGKILL'); } catch (e) {}
        currentProcess = null;
    }
    isPlaying = false;
}

function playStream(song) {
    if (isLiveDJ) return; 

    isPlaying = true;
    const fileName = path.join(config.downloadDir, `${song.id}.mp3`);
    
    client.action(config.channels[0], `🎶 Now Playing: ${song.title} [Req: ${song.requester}]`);
    console.log(`Downloading: ${song.title}`);

    // Siapkan argumen download
    let dlArgs = [
        '--no-warnings',
        '-x', '--audio-format', 'mp3', 
        '-o', fileName, 
        '--force-overwrites'
    ];

    // Tambahkan cookies saat download juga
    if (fs.existsSync(config.cookiesPath)) {
        dlArgs.push('--cookies', config.cookiesPath);
    }

    dlArgs.push(song.url);

    const downloader = spawn(config.ytdlpPath, dlArgs);

    downloader.on('close', (code) => {
        if (isLiveDJ) {
            if(fs.existsSync(fileName)) fs.unlink(fileName, ()=>{});
            isPlaying = false;
            return;
        }

        if (code === 0) {
            const shoutcastUrl = `icecast://${config.scUser}:${config.scPass}@${config.scHost}:${config.scPort}/`;
            
            console.log(`Streaming...`);

            const streamer = spawn(config.ffmpegPath, [
                '-re', '-i', fileName,
                '-acodec', 'libmp3lame', '-ab', '128k', '-ac', '2', '-f', 'mp3', 
                '-content_type', 'audio/mpeg',
                shoutcastUrl
            ]);

            currentProcess = streamer;

            streamer.on('close', () => {
                if(fs.existsSync(fileName)) fs.unlink(fileName, ()=>{});
                isPlaying = false;
                currentProcess = null;
                setTimeout(checkQueue, 1000);
            });
            
            streamer.on('error', () => {
                 stopStreaming();
                 setTimeout(checkQueue, 2000);
            });

        } else {
            client.say(config.channels[0], "Gagal download lagu (Mungkin kena limit/region block).");
            isPlaying = false;
            checkQueue();
        }
    });
}
