// metaAntiSpy.js
/**
 * Detects if your WhatsApp bot account is under Meta surveillance or flagged as suspicious.
 * @param {Object} sock - Baileys socket connection
 * @param {Object} options - Configuration options
 * @returns {Promise<Object>} - Security report
 */
async function metaAntiSpy(sock, options = {}) {
    const {
        verbose = true,
        autoFix = false,
        logger = console
    } = options;

    const report = {
        timestamp: new Date().toISOString(),
        botJid: sock.user.id,
        server: sock.user.id.split('@')[1] || 'unknown',
        riskLevel: 'unknown',
        indicators: [],
        suggestions: [],
        metaActions: []
    };

    // 1. Response time test (Meta can artificially delay suspicious accounts)
    const start = Date.now();
    try {
        await sock.sendMessage(sock.user.id, { text: 'ping' });
        const responseTime = Date.now() - start;
        report.indicators.push({ name: 'response_time', value: responseTime, unit: 'ms' });
        if (responseTime > 5000) {
            report.riskLevel = 'high';
            report.metaActions.push('Unnatural response delay (possible Meta surveillance)');
        }
    } catch (err) {
        report.riskLevel = 'critical';
        report.metaActions.push(`Connection failed: ${err.message}`);
    }

    // 2. Try sending a message to a random existing chat
    if (sock?.store?.chats) {
        const randomChat = Object.values(sock.store.chats)[0];
        if (randomChat?.id) {
            const testMsg = await sock.sendMessage(randomChat.id, { text: '👀 Bot security test' }).catch(e => null);
            if (!testMsg) {
                report.riskLevel = 'high';
                report.metaActions.push('Cannot send messages to existing chats (possibly banned/restricted)');
            }
        }
    }

    // 3. Risk analysis & suggestions
    if (report.riskLevel === 'high' || report.riskLevel === 'critical') {
        report.suggestions.push('🔹 Change the phone number linked to the bot');
        report.suggestions.push('🔹 Use a temporary/virtual number for testing');
        report.suggestions.push('🔹 Reduce messages per minute (add catnap delays)');
        report.suggestions.push('🔹 Switch hosting server (change IP/location)');
        report.suggestions.push('🔹 Enable "slow mode" (random delays between actions)');
    } else if (report.riskLevel === 'unknown') {
        report.suggestions.push('🔹 No major issues detected, but stay cautious.');
        report.suggestions.push('🔹 Avoid sending more than 20 messages per minute.');
    }

    // 4. Auto-fix attempt (experimental)
    if (autoFix && report.riskLevel === 'high') {
        logger.warn('⚠️ Attempting auto-fix (experimental)');
        if (!global._catnapActive) {
            global._catnapActive = true;
            report.suggestions.push('🔹 Auto-activated catnap (2-5s delay between messages)');
        }
    }

    if (verbose) {
        logger.log('📊 Bot Security Report:');
        logger.log(JSON.stringify(report, null, 2));
    }

    return report;
}

module.exports = { metaAntiSpy };
