/**
 * DeepSeek AI Service
 * Provides AI capabilities: scam detection, auto-reply, group greeting
 */
import axios from 'axios';
import consola from 'consola';

const DEEPSEEK_BASE_URL = 'https://api.deepseek.com';
const DEFAULT_MODEL = 'deepseek-chat';

/**
 * Core DeepSeek API caller
 * @param {string} apiKey - DeepSeek API key
 * @param {Array} messages - Chat messages array [{role, content}]
 * @param {string} model - Model name (default: deepseek-chat)
 * @returns {Promise<string>} AI response text
 */
export async function callDeepSeek(apiKey, messages, model = DEFAULT_MODEL) {
    const response = await axios.post(
        `${DEEPSEEK_BASE_URL}/v1/chat/completions`,
        {
            model,
            messages,
            temperature: 0.7,
            max_tokens: 600,
        },
        {
            headers: {
                Authorization: `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
            },
            timeout: 20000,
        }
    );
    return response.data?.choices?.[0]?.message?.content?.trim() || '';
}

/**
 * Detect scam/penipuan in message using AI
 * @param {string} apiKey
 * @param {string} messageText
 * @returns {Promise<{isScam: boolean, confidence: number, reason: string}>}
 */
export async function detectScam(apiKey, messageText) {
    try {
        const content = await callDeepSeek(apiKey, [
            {
                role: 'system',
                content:
                    'Anda adalah pakar keselamatan siber Malaysia. Analisa mesej WhatsApp berikut dan tentukan sama ada ia scam atau penipuan. ' +
                    'Balas HANYA dalam format JSON tanpa markdown: {"isScam":true,"confidence":85,"reason":"sebab ringkas BM"}. ' +
                    'confidence adalah 0-100. Jangan tambah teks lain.',
            },
            {
                role: 'user',
                content: `Analisa mesej ini:\n"${String(messageText).substring(0, 1000)}"`,
            },
        ]);

        // Strip markdown code blocks if any
        const cleaned = content.replace(/```[a-z]*\n?|\n?```/gi, '').trim();
        const parsed = JSON.parse(cleaned);
        return {
            isScam: !!parsed.isScam,
            confidence: parseInt(parsed.confidence || 0),
            reason: String(parsed.reason || '').substring(0, 200),
        };
    } catch (e) {
        consola.warn('[DeepSeek] detectScam failed:', e.message);
        return { isScam: false, confidence: 0, reason: '' };
    }
}

/**
 * Generate AI greeting for new group member
 * @param {string} apiKey
 * @param {string} memberName - New member name/phone
 * @param {string} groupName - Group name
 * @param {string} customPrompt - Custom system prompt (optional)
 * @returns {Promise<string>} Greeting message
 */
export async function generateGreeting(apiKey, memberName, groupName, customPrompt) {
    try {
        const systemPrompt =
            customPrompt ||
            'Anda adalah bot WhatsApp yang mesra dan profesional. Tulis ucapan selamat datang yang ringkas, mesra dan menarik dalam Bahasa Malaysia untuk ahli baru group. Maksimum 3 ayat pendek. Gunakan 1-2 emoji yang sesuai sahaja.';

        const content = await callDeepSeek(apiKey, [
            { role: 'system', content: systemPrompt },
            {
                role: 'user',
                content: `Ahli baru "${memberName}" baru sahaja menyertai group WhatsApp bernama "${groupName}". Tulis ucapan selamat datang.`,
            },
        ]);
        return content;
    } catch (e) {
        consola.warn('[DeepSeek] generateGreeting failed:', e.message);
        return `👋 Selamat datang *${memberName}* ke *${groupName}*! Semoga seronok bersama kami. 😊`;
    }
}

/**
 * Generate AI auto-reply for incoming message
 * @param {string} apiKey
 * @param {string} messageText - User's message
 * @param {string} systemPrompt - Custom system prompt (optional)
 * @returns {Promise<string|null>} Reply text, or null on failure
 */
export async function generateAutoReply(apiKey, messageText, systemPrompt) {
    try {
        const sysPrompt =
            systemPrompt ||
            'Anda adalah asisten WhatsApp yang membantu dan mesra. Balas dalam Bahasa Malaysia dengan ringkas, tepat dan bermakluma. Maksimum 150 patah perkataan. Jangan sebut bahawa anda adalah AI melainkan ditanya.';

        const content = await callDeepSeek(apiKey, [
            { role: 'system', content: sysPrompt },
            { role: 'user', content: String(messageText).substring(0, 2000) },
        ]);
        return content || null;
    } catch (e) {
        consola.warn('[DeepSeek] generateAutoReply failed:', e.message);
        return null;
    }
}

/**
 * Test API key validity
 * @param {string} apiKey
 * @returns {Promise<{valid: boolean, message: string}>}
 */
export async function testApiKey(apiKey) {
    try {
        const content = await callDeepSeek(
            apiKey,
            [{ role: 'user', content: 'Balas dengan perkataan "OK" sahaja.' }],
            DEFAULT_MODEL
        );
        return { valid: !!content, message: 'API key sah dan berfungsi.' };
    } catch (e) {
        const msg = e.response?.data?.error?.message || e.message || 'Ralat tidak diketahui';
        return { valid: false, message: `API key tidak sah: ${msg}` };
    }
}
