// app/api/telegram/lib/config.ts
import { Telegraf } from 'telegraf';
import { Pinecone } from '@pinecone-database/pinecone';
import { PrismaMemory as PrismaMemoryClass } from './prisma-memory';
import { createCustomLLM as createCustomLLMFunction } from './llm';
import { GET as getLiteralsFromRoute } from "../../rag/literals/route";
import { prisma } from '@/lib/prisma';



export let bot: Telegraf;
export let memory: PrismaMemoryClass;
export let customLLM: ReturnType<typeof createCustomLLMFunction>;
export let pineconeIndex: any;
export let pc: Pinecone;

// Control flags - keep these private to this module
let _botInitialized = false;
let _isLaunching = false;
let _coreServicesInitialized = false;

// Getters and setters for state variables
export const getBotInitialized = () => _botInitialized;
export const setBotInitialized = (value: boolean) => { _botInitialized = value; };

export const getIsLaunching = () => _isLaunching;
export const setIsLaunching = (value: boolean) => { _isLaunching = value; };

export const getCoreServicesInitialized = () => _coreServicesInitialized;
export const setCoreServicesInitialized = (value: boolean) => { _coreServicesInitialized = value; };

export async function initializeCoreServices() {
    if (_coreServicesInitialized) return;
    const panelSetting = await prisma.panelSetting.findFirst({
        select: {
            telegramBotToken: true,
            pineconeIndexName: true,
            pineconeNamespace: true
        }
    });
    
    const telegramBotToken = panelSetting?.telegramBotToken || process.env.TELEGRAM_BOT_TOKEN;
    if (!telegramBotToken) {
        console.error("ERROR: Telegram bot token not found in database or environment variables");
        throw new Error("Telegram bot token not found");
    }
    
    // Get Pinecone index and namespace from database or use defaults
    const indexName = panelSetting?.pineconeIndexName || "firms-index";
    const namespace = panelSetting?.pineconeNamespace || "main-namespace";
    
    console.log("🤖 Initializing Telegram bot");
    bot = new Telegraf(telegramBotToken);
    memory = new PrismaMemoryClass();
    
    // Initialize Pinecone with the retrieved values
    pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY as string });
    pineconeIndex = pc.index(indexName).namespace(namespace);
    
    const literalModel = await prisma.literals.findFirst({
        select: {
            aiModel: true
        },
        orderBy: { id: 'desc' }
    });
    const aiModel = literalModel?.aiModel || "google/gemini-2.0-flash-lite-001";
    console.log(`🤖 Using AI model: ${aiModel} 🤖`);
    customLLM = createCustomLLMFunction(
        process.env.OPENROUTER_API_KEY as string,
        aiModel
    );
    _coreServicesInitialized = true;
}

export async function stopBot() {
    if (!bot) return;
    
    try {
        // If in production mode, delete the webhook
        if (process.env.MODE === 'prod') {
            await bot.telegram.deleteWebhook();
            console.log('Webhook deleted for restart.');
        } 
        // If in polling mode, stop the bot
        else if ((bot as any).polling?.abortController) {
            bot.stop('RESTART');
            console.log('Bot polling stopped for restart.');
        }
    } catch (error) {
        console.error('Error stopping bot:', error);
    }
}

export async function getLiterals() {
    try {
        const literalsResponse = await getLiteralsFromRoute();
        if (!literalsResponse.ok) {
            const errorText = await literalsResponse.text();
            console.error(`Failed to fetch literals: ${literalsResponse.status} ${literalsResponse.statusText}`, errorText);
            return {
                welcomeText: "خوش آمدید! (خطا در بارگذاری)",
                commands: [],
                finalPrompt: "خطا: قالب اولیه در دسترس نیست. سوال شما: {question}"
            };
        }
        return await literalsResponse.json();
    } catch (error) {
        console.error("Error fetching or parsing literals:", error);
        return {
            welcomeText: "خوش آمدید! (خطای سیستمی)",
            commands: [],
            finalPrompt: "خطای سیستمی: قالب اولیه در دسترس نیست. سوال شما: {question}"
        };
    }
}