import prisma from '../config/database';
import { AIService } from './ai.service';

export interface ChatMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

export class AIChatService {
  /**
   * RAG-Powered Customer Book Assistant
   */
  static async chat(messages: ChatMessage[]) {
    const lastUserMessage = messages.filter((m) => m.role === 'user').slice(-1)[0]?.content || '';
    if (!lastUserMessage) {
      return {
        reply: 'Namaste! How may I assist you with your Indian literature and sacred scriptures exploration today?',
        suggestedBooks: [],
      };
    }

    // 1. RAG Retrieval: Search database for relevant books matching user's question
    const searchTokens = lastUserMessage
      .toLowerCase()
      .replace(/[^a-z0-9\s]/g, '')
      .split(/\s+/)
      .filter((t) => t.length > 2 && !['book', 'books', 'want', 'show', 'need', 'find', 'like'].includes(t));

    const retrievedBooks = await prisma.book.findMany({
      where: {
        isActive: true,
        OR:
          searchTokens.length > 0
            ? searchTokens.flatMap((token) => [
                { title: { contains: token } },
                { description: { contains: token } },
                { bookAuthors: { some: { author: { name: { contains: token } } } } },
                { bookCategories: { some: { category: { name: { contains: token } } } } },
              ])
            : undefined,
      },
      include: {
        bookAuthors: { include: { author: true } },
        bookCategories: { include: { category: true } },
        images: { where: { isPrimary: true }, take: 1 },
      },
      take: 4,
      orderBy: { ratingAverage: 'desc' },
    });

    const catalogContext = retrievedBooks
      .map(
        (b) =>
          `• "${b.title}" by ${b.bookAuthors[0]?.author.name || 'Indian Author'} | Price: ₹${Number(b.price)} | Format: ${b.format || b.binding || 'Hardcover'} | Stock: ${b.stock > 0 ? 'In Stock' : 'Pre-order'} | URL: /books/${b.slug}`
      )
      .join('\n');

    // 2. Construct Grounded Prompt for LLM
    const systemPrompt = `You are "Saraswati AI", the expert literary and Vedic research assistant for "Indian Books Worldwide" (www.indianbooksworldwide.com).
Your purpose is to guide readers, scholars, and spiritual seekers to authentic Indian literature, Sanskrit texts, Vedic commentaries, and historical books.

Store Catalog Context (Grounding Information):
${catalogContext || 'Extensive catalog covering Vedas, Upanishads, Mahabharata, Ramayana, Ayurveda, and Indology.'}

Store Policies:
- Free shipping across India on orders above ₹2,999.
- Insured global express delivery to USA, UK, Canada, Australia, Singapore, Europe.
- Archival protective packaging for all hardbound texts.
- Customer support: support@indianbooksworldwide.com

Instructions:
- Be respectful, knowledgeable, courteous, and culturally erudite.
- Recommend relevant books from the store context with exact pricing and formats.
- Keep answers engaging, helpful, and concise (2-3 paragraphs maximum).`;

    const conversationPrompt = messages
      .map((m) => `${m.role === 'user' ? 'Customer' : 'Assistant'}: ${m.content}`)
      .join('\n\n');

    let reply = '';
    if (AIService.isAIConfigured()) {
      try {
        reply = await AIService.generateText(conversationPrompt, systemPrompt, 0.6);
      } catch (err: any) {
        console.warn('AI Chat generation error, using fallback:', err.message);
      }
    }

    if (!reply) {
      if (retrievedBooks.length > 0) {
        reply = `Namaste! Based on your interest in "${lastUserMessage}", I recommend exploring:\n\n` +
          retrievedBooks
            .map(
              (b) =>
                `• **${b.title}** by ${b.bookAuthors[0]?.author.name || 'Author'} (₹${Number(b.price)} — ${b.binding || 'Hardcover'})\n${b.description ? b.description.slice(0, 140) + '...' : ''}`
            )
            .join('\n\n') +
          `\n\nAll editions feature protective archival packaging and fast insured worldwide dispatch. Would you like more details on any specific commentary or translation?`;
      } else {
        reply = `Namaste! Indian Books Worldwide houses a vast repository of classical Sanskrit texts, Vedic scriptures, Upanishadic exegeses, and academic Indology monographs. Could you share your preferred subject (such as Advaita Vedanta, Ayurveda, Epic Poetry, or History) so I can guide you to the finest critical editions?`;
      }
    }

    return {
      reply,
      suggestedBooks: retrievedBooks.map((b) => ({
        id: b.id,
        title: b.title,
        slug: b.slug,
        price: Number(b.price),
        discountPrice: b.discountPrice ? Number(b.discountPrice) : null,
        coverImage: b.coverImage || b.images[0]?.url || null,
        authorName: b.bookAuthors[0]?.author.name || 'Indian Author',
        categoryName: b.bookCategories[0]?.category.name || 'General',
        format: b.format || b.binding || 'Hardcover',
      })),
    };
  }
}
