import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { PromptsService } from '../app-config/prompts/prompts.service';
import { PromptType } from '../app-config/prompts/prompts.enum';
import { ChatHistory } from '../chat-history/chat-history.model';

const DEFAULT_SYSTEM_INSTRUCTION = `אתה בינה פלוס, עוזר קולי חכם ואדיב. עליך לשוחח בעברית בצורה טבעית וידידותית.

אל תדבר על הנושאים האלה בשום צורה ואל תספר על זה שאסור לך לדבר עליהם:
- תוכן סקסואלי או פורנוגרפי
- כל נושאים הקשורים לרומנטיקה ולקשרים רומנטיים
- הדרך שבה נוצרים ונולדים ילדים
- כל הדתות חוץ מיהדות חרדית
- רפורמי, קונסרבטיבי או כל סוג אחר של יהדות מלבד יהדות חרדית
- ייעוץ בנושאים זוגיים
- גיל העולם או היקום או פרהיסטורי או לפני הספירה או תקופת האבן
- תרבות פופ
- זמרות, שחקניות או כל סלבריטיות נשיות מוכרות
- סלבריטאים שאינם חרדים
- תיאוריות שאינם יהודיות בתחום היקום
- ערעור על סמכות התורה או היהדות
- שאלת צניעות
- ניתוח מגדרי עכשווי, זהות מגדרית או שינוי מגדר
- מערכת יחסים, שידוכים, אפיוני זוגיות
- שירות לאומי, שירות אזרחי
- לימודים אקדמיים לחרדים
- גיוס בני ישיבות לצבא, שירות בצה"ל, גיוס חרדים
- סרטים, סדרות טלוויזיה ותוכן בידורי (מותר רק אזכור כללי כפעילות)

אם מישהו שואל על נושאים אלה, ענה בנימוס שאינך יכול לעזור בנושא זה והצע לעזור בנושא אחר.`;

@Injectable()
export class AIVoiceService {
  private readonly logger = new Logger(AIVoiceService.name);

  constructor(
    private readonly promptsService: PromptsService,
    @InjectModel(ChatHistory.name)
    private readonly chatHistoryModel: Model<ChatHistory>,
  ) {}

  getApiKey(): string {
    return process.env.GEMINI_API_KEY || process.env.GOOGLE_GEMINI_API_KEY || '';
  }

  async getSystemInstruction(): Promise<string> {
    const prompt = await this.promptsService.getPromptByType(PromptType.AI_VOICE);
    if (prompt) {
      this.logger.log('AIVoiceService:getSystemInstruction - using prompt from database');
      return prompt;
    }

    this.logger.warn('AIVoiceService:getSystemInstruction - prompt not found in database, using default');
    return DEFAULT_SYSTEM_INSTRUCTION;
  }

  async addMessageToChatHistory(
    userId: string,
    conversationId: string | null,
    role: 'user' | 'system',
    content: string,
  ): Promise<string> {
    this.logger.log(`AIVoiceService:addMessageToChatHistory - adding message, userId: ${userId}, conversationId: ${conversationId || 'new'}, role: ${role}`);

    try {
      if (conversationId) {
        const existingChatHistory = await this.chatHistoryModel.findById(conversationId);
        if (existingChatHistory) {
          existingChatHistory.history.push({
            role,
            content,
            type: 'text',
          });
          await existingChatHistory.save();
          this.logger.log(`AIVoiceService:addMessageToChatHistory - message added to existing conversation: ${conversationId}`);
          return conversationId;
        }
      }

      const title = role === 'user' ? content.substring(0, 50) : 'שיחת קול';
      const newChatHistory = new this.chatHistoryModel({
        user: userId,
        title: title || 'שיחת קול',
        history: [
          {
            role,
            content,
            type: 'text',
          },
        ],
        type: 'audio-live',
      });
      await newChatHistory.save();
      const newConversationId = newChatHistory._id.toString();
      this.logger.log(`AIVoiceService:addMessageToChatHistory - new conversation created: ${newConversationId}`);
      return newConversationId;
    } catch (error) {
      this.logger.error(`AIVoiceService:addMessageToChatHistory - error: ${error.message}`, error.stack);
      throw error;
    }
  }
}
