// app/api/telegram/lib/services.ts
import { prisma } from '@/lib/prisma'; // استفاده از singleton prisma
import { Telegraf } from 'telegraf';
import { PrismaMemory as PrismaMemoryClass } from './prisma-memory';
import { createCustomLLM as createCustomLLMFunction } from './llm';

// Create a singleton pattern with state management
class BotServices {
  private static instance: BotServices;
  
  // حذف prisma از کلاس چون الان از singleton استفاده می‌کنیم
  bot: Telegraf | null = null;
  memory: PrismaMemoryClass | null = null;
  customLLM: ReturnType<typeof createCustomLLMFunction> | null = null;
  
  botInitialized = false;
  isLaunching = false;
  coreServicesInitialized = false;

  private constructor() {
  }

  public static getInstance(): BotServices {
    if (!BotServices.instance) {
      BotServices.instance = new BotServices();
    }
    return BotServices.instance;
  }

  public reset() {
    // حذف prisma از reset چون الان singleton است
    this.bot = null;
    this.memory = null;
    this.customLLM = null;
    this.botInitialized = false;
    this.isLaunching = false;
    this.coreServicesInitialized = false;
  }

  async initializeCoreServices() {
    if (this.coreServicesInitialized) return;
    
    // استفاده از singleton prisma
    const panelSetting = await prisma.panelSetting.findFirst({
      select: {
        telegramBotToken: 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");
    }
    
    console.log("🤖 Initializing Telegram bot");
    this.bot = new Telegraf(telegramBotToken);
    this.memory = new PrismaMemoryClass();
    
    // استفاده از singleton prisma
    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} 🤖`);
    
    this.customLLM = createCustomLLMFunction(
      process.env.OPENROUTER_API_KEY as string,
      aiModel
    );
    
    this.coreServicesInitialized = true;
  }

  async stopBot() {
    if (!this.bot) return;

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

// Export a singleton instance
export const services = BotServices.getInstance();

// Export convenience getters
export const getPrisma = () => prisma; // تغییر به singleton prisma
export const getBot = () => services.bot;
export const getMemory = () => services.memory;
export const getCustomLLM = () => services.customLLM;