// app/api/telegram/lib/message-processor.ts
import { searchPinecone } from './pinecone-search';
import { memory, customLLM } from './config'; // Removed 'prompt' import
import { ChatPromptTemplate } from '@langchain/core/prompts'; // Import for dynamic prompt creation

export async function processMessage(ctx: any, message: string, currentLiterals: any) {
    try {
        if (!memory || !customLLM) {
            console.error("Core services (memory/LLM) not initialized in processMessage. This should not happen.");
            await ctx.reply('سیستم در حال راه اندازی اولیه است، لطفا چند لحظه دیگر تلاش کنید.');
            return;
        }
        if (!currentLiterals || !currentLiterals.finalPrompt) {
            console.error("Literals or finalPrompt is missing in processMessage. Literals:", currentLiterals);
            await ctx.reply('خطا در بارگذاری تنظیمات پیام. لطفا بعدا تلاش کنید.');
            return;
        }


        await memory.saveMessage(ctx.chat.id, 'user', message, ctx.from);
        const user = await memory.getOrCreateUser(ctx.from);
        if (user.respondent != 'ai') {
            return;
        }
        await ctx.telegram.sendChatAction(ctx.chat.id, 'typing');
        const searchResults = await searchPinecone(message);
        const chatHistoryText = await memory.getChatHistory(ctx.chat.id, ctx.from);
        const dynamicPrompt = ChatPromptTemplate.fromTemplate(currentLiterals.finalPrompt);
        const fullPrompt = await dynamicPrompt.format({
            chat_history: chatHistoryText,
            context: searchResults.contextText || "اطلاعات مرتبطی یافت نشد.",
            question: message
        });
        const answer = await customLLM.invoke({ prompt: fullPrompt });
        await memory.saveMessage(ctx.chat.id, 'assistant', answer, ctx.from);
        await ctx.reply(answer);

    } catch (error) {
        console.error('Error processing message:', error);
        await ctx.reply('متأسفانه در پردازش پیام شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.');
    }
}