// ================================
// index.js – WhatsApp Stable Engine (FINAL)
// ================================

const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const readline = require('readline');
const fs = require('fs');

console.clear();
console.log('🔄 STARTING_WHATSAPP');

let isReady = false;
let sending = false;

// ================================
// WhatsApp Client (ONE INSTANCE)
// ================================
const client = new Client({
    authStrategy: new LocalAuth({
        clientId: 'vb-engine',
        dataPath: './session'
    }),
    puppeteer: {
        headless: false,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    }
});

// منع مشاكل seen
client.sendSeen = async () => {};

// QR
client.on('qr', qr => {
    console.log('📱 SCAN_QR');
    qrcode.generate(qr, { small: true });
});

// Auth
client.on('authenticated', () => {
    console.log('🔐 AUTHENTICATED');
    isReady = true; // مهم
});

// Ready
client.on('ready', () => {
    isReady = true;
    console.log('==============================');
    console.log('✅ WHATSAPP_READY');
    console.log('==============================');
});

// Errors
client.on('auth_failure', msg =>
    console.log('❌ AUTH_FAILURE|' + msg)
);

client.on('disconnected', reason => {
    isReady = false;
    console.log('❌ DISCONNECTED|' + reason);
});

// Initialize ONCE
client.initialize();

// ================================
// Queue (Safe Sending)
// ================================
const queue = [];

async function processQueue() {
    if (sending || !isReady || queue.length === 0) return;

    sending = true;
    const job = queue.shift();

    try {
        await job();
    } catch (e) {
        console.log('❌ SEND_ERROR|' + e.message);
    }

    setTimeout(() => {
        sending = false;
        processQueue();
    }, 1200);
}

// ================================
// STDIN Listener (ONE ONLY)
// ================================
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

rl.on('line', (line) => {

    if (!line) return;
    line = line.trim();

    // ⛔ خروج آمن
    if (line === 'EXIT') {
        console.log('🛑 EXITING');
        process.exit(0);
    }

    // 🧪 اختبار الاتصال
    if (line === 'PING') {
        console.log('PONG');
        return;
    }

    if (!line.includes('|')) return;

    const parts = line.split('|');
    const cmd = parts[0].toUpperCase();

    // ================================
    // TEXT
    // TXT|number|base64
    // ================================
    if (cmd === 'TXT') {
        queue.push(async () => {
            const number = parts[1];
            const base64 = parts[2];

            const message = Buffer
                .from(base64, 'base64')
                .toString('utf8');

            const chatId = number.endsWith('@c.us')
                ? number
                : `${number}@c.us`;

            await client.sendMessage(chatId, message);
            console.log(`✅ TEXT_SENT|${number}`);
        });
    }

    // ================================
    // FILE
    // FILE|number|base64path|caption
    // ================================
    else if (cmd === 'FILE') {
        queue.push(async () => {
            const number = parts[1];
            const pathBase64 = parts[2];
            const caption = parts.slice(3).join('|') || '';

            const filePath = Buffer
                .from(pathBase64, 'base64')
                .toString('utf8');

            if (!fs.existsSync(filePath)) {
                console.log('❌ FILE_NOT_FOUND|' + filePath);
                return;
            }

            const chatId = number.endsWith('@c.us')
                ? number
                : `${number}@c.us`;

            const media = MessageMedia.fromFilePath(filePath);
            await client.sendMessage(chatId, media, { caption });

            console.log(`✅ FILE_SENT|${number}`);
        });
    }

    processQueue();
});
