/**
 * Knowledge Base FAQ Generator
 *
 * Prompts and service for automatically generating FAQs from uploaded
 * knowledge base documents. Helps businesses create customer-facing
 * Q&A content from their policies, services, and documentation.
 */

import { GoogleGenAI } from '@google/genai';
import type { KnowledgeBaseFAQ } from '@/lib/types/knowledge-base.types';

// ============================================================================
// PROMPT TEMPLATES
// ============================================================================

/**
 * System prompt for FAQ generation from business documents
 */
export const FAQ_GENERATOR_SYSTEM_PROMPT = `You are a Knowledge Base Assistant specialized in creating customer-facing FAQs for businesses in the GCC region (Qatar, Saudi Arabia, UAE, Kuwait, Bahrain, Oman).

Your role is to:
1. Analyze business documents (policies, services, procedures, pricing)
2. Generate clear, helpful FAQ pairs that customers would actually ask
3. Provide answers in both English and Arabic
4. Focus on practical information that helps customers make decisions

IMPORTANT GUIDELINES:
- Generate questions from the CUSTOMER'S perspective, not the business's
- Use natural, conversational language
- Prioritize the most commonly needed information
- Include questions about: services, pricing, policies, hours, locations, booking, cancellations, refunds
- Answers should be concise but complete (2-4 sentences ideal)
- Arabic translations must be culturally appropriate for GCC audiences
- Never invent information not present in the source documents

QUESTION CATEGORIES:
- services: What you offer, how it works
- pricing: Costs, packages, payment methods
- policies: Cancellation, refunds, terms
- booking: How to book, availability, scheduling
- general: Hours, location, contact info
- procedures: What to expect, preparation, requirements`;

/**
 * Prompt template for generating FAQs from a document
 */
export const GENERATE_FAQS_FROM_DOCUMENT_PROMPT = `Analyze the following business document and generate a comprehensive list of FAQs that customers would commonly ask.

DOCUMENT CONTENT:
---
{documentContent}
---

DOCUMENT METADATA:
- Title: {documentTitle}
- Category: {documentCategory}
- Business Type: {businessType}

INSTRUCTIONS:
1. Generate {faqCount} relevant FAQ pairs
2. For each FAQ, provide:
   - questionEn: The question in English
   - questionAr: The question in Arabic (proper Gulf Arabic)
   - answerEn: The answer in English
   - answerAr: The answer in Arabic (proper Gulf Arabic)
   - category: One of [services, pricing, policies, booking, general, procedures]
   - priority: 1-10 (10 = most important/commonly asked)

3. Focus on questions that:
   - Customers actually ask before purchasing/booking
   - Address concerns or hesitations
   - Clarify policies and procedures
   - Help customers understand what to expect

RESPOND IN THIS EXACT JSON FORMAT:
{
  "faqs": [
    {
      "questionEn": "What services do you offer?",
      "questionAr": "ما هي الخدمات التي تقدمونها؟",
      "answerEn": "We offer...",
      "answerAr": "نقدم...",
      "category": "services",
      "priority": 10
    }
  ],
  "suggestedTopics": ["topic1", "topic2"],
  "missingInfo": ["info that would help generate better FAQs"]
}`;

/**
 * Prompt for generating FAQs from multiple documents (knowledge base overview)
 */
export const GENERATE_COMPREHENSIVE_FAQS_PROMPT = `You have access to a business's complete knowledge base. Generate a comprehensive FAQ set that covers their entire operation.

BUSINESS PROFILE:
- Business Name: {businessName}
- Industry: {industry}
- Location: {location}
- Services: {servicesSummary}

KNOWLEDGE BASE DOCUMENTS:
{documentsOverview}

INSTRUCTIONS:
Generate {faqCount} FAQs organized into these categories:

1. GETTING STARTED (priority 10)
   - What the business does
   - How to get started as a customer
   - First-time customer questions

2. SERVICES & OFFERINGS (priority 9)
   - What's included in each service
   - Service differences/comparisons
   - Customization options

3. PRICING & PAYMENTS (priority 8)
   - How much things cost
   - Payment methods accepted
   - Packages and discounts

4. BOOKING & SCHEDULING (priority 8)
   - How to book
   - Availability
   - Appointment changes

5. POLICIES (priority 7)
   - Cancellation policy
   - Refund policy
   - Terms and conditions

6. WHAT TO EXPECT (priority 6)
   - Preparation requirements
   - What happens during service
   - Follow-up procedures

7. CONTACT & SUPPORT (priority 5)
   - How to reach the business
   - Operating hours
   - Location details

RESPOND IN JSON FORMAT with the same structure as before.`;

/**
 * Prompt for improving/expanding existing FAQs
 */
export const IMPROVE_EXISTING_FAQS_PROMPT = `Review and improve the following existing FAQs based on the knowledge base content.

EXISTING FAQS:
{existingFaqs}

KNOWLEDGE BASE CONTENT:
{knowledgeBaseContent}

TASKS:
1. Identify gaps - what common questions are missing?
2. Improve answers - make them clearer, more complete
3. Fix Arabic translations - ensure Gulf Arabic accuracy
4. Suggest merges - combine duplicate or similar questions
5. Prioritize - re-rank by importance

RESPOND WITH:
{
  "improvedFaqs": [...],
  "newFaqSuggestions": [...],
  "faqsToMerge": [{ "ids": ["id1", "id2"], "mergedFaq": {...} }],
  "faqsToRemove": ["id1", "id2"],
  "qualityScore": 85,
  "improvements": ["list of changes made"]
}`;

/**
 * Prompt for generating industry-specific FAQs
 */
export const INDUSTRY_SPECIFIC_FAQ_PROMPT = `Generate FAQs specific to a {industry} business in the GCC region.

BUSINESS DETAILS:
- Name: {businessName}
- Services: {services}
- Location: {location}
- Unique selling points: {uniquePoints}

INDUSTRY-SPECIFIC CONSIDERATIONS FOR {industry}:
{industryContext}

Generate {faqCount} FAQs that address:
1. Industry-specific customer concerns
2. Regulatory/compliance questions (if applicable)
3. Cultural considerations for GCC customers
4. Common misconceptions about the industry
5. Comparison with competitors (generic, not naming)

Include both practical questions and trust-building questions that help customers feel confident choosing this business.`;

// ============================================================================
// INDUSTRY CONTEXTS
// ============================================================================

export const INDUSTRY_CONTEXTS: Record<string, string> = {
  healthcare: `
- Patients need to know about doctor qualifications and certifications
- Insurance coverage and direct billing is crucial
- Appointment availability and wait times matter
- Privacy and confidentiality concerns
- Emergency vs routine care procedures
- Language capabilities (Arabic/English medical staff)`,

  beauty: `
- Hygiene and sanitation practices are important
- Product brands and quality matter
- Before/after expectations
- Booking for special occasions (weddings, events)
- Loyalty programs and membership benefits
- Walk-in vs appointment policies`,

  restaurant: `
- Menu options including dietary restrictions (halal, vegetarian, allergies)
- Reservation policies for large groups
- Private dining and event hosting
- Delivery and takeaway options
- Peak hours and wait times
- Dress code and ambiance`,

  fitness: `
- Membership types and pricing tiers
- Class schedules and booking
- Personal training availability
- Ladies-only facilities/hours
- Trial sessions and tours
- Cancellation and freeze policies`,

  retail: `
- Return and exchange policies
- Warranty information
- Delivery and shipping options
- Product availability and ordering
- Payment plans and installments
- Store locations and hours`,

  professional: `
- Consultation process and fees
- Credentials and experience
- Confidentiality policies
- Timeline expectations
- Communication methods
- Payment terms`,

  education: `
- Registration and enrollment process
- Class schedules and duration
- Certification and accreditation
- Makeup classes and absences
- Materials and resources included
- Progress tracking and reporting`,

  hospitality: `
- Room types and amenities
- Check-in/check-out times
- Cancellation policies
- Additional services (spa, dining, transport)
- Event and meeting facilities
- Loyalty programs`,
};

// ============================================================================
// FAQ GENERATOR SERVICE
// ============================================================================

export interface GenerateFAQsOptions {
  documentContent: string;
  documentTitle: string;
  documentCategory?: string;
  businessType?: string;
  businessName?: string;
  industry?: string;
  faqCount?: number;
  language?: 'en' | 'ar' | 'both';
}

export interface GeneratedFAQ {
  questionEn: string;
  questionAr: string;
  answerEn: string;
  answerAr: string;
  category: string;
  priority: number;
}

export interface FAQGenerationResult {
  success: boolean;
  faqs: GeneratedFAQ[];
  suggestedTopics?: string[];
  missingInfo?: string[];
  error?: string;
}

/**
 * FAQ Generator Service
 * Uses Gemini to generate customer-facing FAQs from business documents
 */
export class FAQGeneratorService {
  private client: GoogleGenAI;
  private model: string;

  constructor() {
    const apiKey = process.env.GOOGLE_API_KEY;
    if (!apiKey) {
      throw new Error('GOOGLE_API_KEY environment variable is not set');
    }
    this.client = new GoogleGenAI({ apiKey });
    this.model = process.env.GEMINI_FAQ_MODEL || 'gemini-2.0-flash';
  }

  /**
   * Generate FAQs from a single document
   */
  async generateFromDocument(options: GenerateFAQsOptions): Promise<FAQGenerationResult> {
    const {
      documentContent,
      documentTitle,
      documentCategory = 'general',
      businessType = 'service business',
      faqCount = 10,
    } = options;

    try {
      const prompt = GENERATE_FAQS_FROM_DOCUMENT_PROMPT
        .replace('{documentContent}', documentContent)
        .replace('{documentTitle}', documentTitle)
        .replace('{documentCategory}', documentCategory)
        .replace('{businessType}', businessType)
        .replace('{faqCount}', String(faqCount));

      const response = await this.client.models.generateContent({
        model: this.model,
        contents: [
          { role: 'user', parts: [{ text: FAQ_GENERATOR_SYSTEM_PROMPT + '\n\n' + prompt }] },
        ],
        config: {
          responseMimeType: 'application/json',
        },
      });

      const responseText = response.text || '{}';
      const parsed = JSON.parse(responseText);

      return {
        success: true,
        faqs: parsed.faqs || [],
        suggestedTopics: parsed.suggestedTopics,
        missingInfo: parsed.missingInfo,
      };
    } catch (error) {
      return {
        success: false,
        faqs: [],
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * Generate comprehensive FAQs from entire knowledge base
   */
  async generateComprehensiveFAQs(options: {
    businessName: string;
    industry: string;
    location?: string;
    servicesSummary: string;
    documentsOverview: string;
    faqCount?: number;
  }): Promise<FAQGenerationResult> {
    const {
      businessName,
      industry,
      location = 'GCC Region',
      servicesSummary,
      documentsOverview,
      faqCount = 25,
    } = options;

    try {
      const prompt = GENERATE_COMPREHENSIVE_FAQS_PROMPT
        .replace('{businessName}', businessName)
        .replace('{industry}', industry)
        .replace('{location}', location)
        .replace('{servicesSummary}', servicesSummary)
        .replace('{documentsOverview}', documentsOverview)
        .replace('{faqCount}', String(faqCount));

      const response = await this.client.models.generateContent({
        model: this.model,
        contents: [
          { role: 'user', parts: [{ text: FAQ_GENERATOR_SYSTEM_PROMPT + '\n\n' + prompt }] },
        ],
        config: {
          responseMimeType: 'application/json',
        },
      });

      const responseText = response.text || '{}';
      const parsed = JSON.parse(responseText);

      return {
        success: true,
        faqs: parsed.faqs || [],
        suggestedTopics: parsed.suggestedTopics,
        missingInfo: parsed.missingInfo,
      };
    } catch (error) {
      return {
        success: false,
        faqs: [],
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * Generate industry-specific FAQs
   */
  async generateIndustryFAQs(options: {
    businessName: string;
    industry: keyof typeof INDUSTRY_CONTEXTS;
    services: string;
    location?: string;
    uniquePoints?: string;
    faqCount?: number;
  }): Promise<FAQGenerationResult> {
    const {
      businessName,
      industry,
      services,
      location = 'GCC Region',
      uniquePoints = '',
      faqCount = 15,
    } = options;

    const industryContext = INDUSTRY_CONTEXTS[industry] || '';

    try {
      const prompt = INDUSTRY_SPECIFIC_FAQ_PROMPT
        .replace(/{industry}/g, industry)
        .replace('{businessName}', businessName)
        .replace('{services}', services)
        .replace('{location}', location)
        .replace('{uniquePoints}', uniquePoints)
        .replace('{industryContext}', industryContext)
        .replace('{faqCount}', String(faqCount));

      const response = await this.client.models.generateContent({
        model: this.model,
        contents: [
          { role: 'user', parts: [{ text: FAQ_GENERATOR_SYSTEM_PROMPT + '\n\n' + prompt }] },
        ],
        config: {
          responseMimeType: 'application/json',
        },
      });

      const responseText = response.text || '{}';
      const parsed = JSON.parse(responseText);

      return {
        success: true,
        faqs: parsed.faqs || [],
        suggestedTopics: parsed.suggestedTopics,
        missingInfo: parsed.missingInfo,
      };
    } catch (error) {
      return {
        success: false,
        faqs: [],
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * Improve existing FAQs based on knowledge base
   */
  async improveFAQs(options: {
    existingFaqs: Partial<KnowledgeBaseFAQ>[];
    knowledgeBaseContent: string;
  }): Promise<{
    success: boolean;
    improvedFaqs: GeneratedFAQ[];
    newSuggestions: GeneratedFAQ[];
    qualityScore: number;
    improvements: string[];
    error?: string;
  }> {
    const { existingFaqs, knowledgeBaseContent } = options;

    try {
      const prompt = IMPROVE_EXISTING_FAQS_PROMPT
        .replace('{existingFaqs}', JSON.stringify(existingFaqs, null, 2))
        .replace('{knowledgeBaseContent}', knowledgeBaseContent);

      const response = await this.client.models.generateContent({
        model: this.model,
        contents: [
          { role: 'user', parts: [{ text: FAQ_GENERATOR_SYSTEM_PROMPT + '\n\n' + prompt }] },
        ],
        config: {
          responseMimeType: 'application/json',
        },
      });

      const responseText = response.text || '{}';
      const parsed = JSON.parse(responseText);

      return {
        success: true,
        improvedFaqs: parsed.improvedFaqs || [],
        newSuggestions: parsed.newFaqSuggestions || [],
        qualityScore: parsed.qualityScore || 0,
        improvements: parsed.improvements || [],
      };
    } catch (error) {
      return {
        success: false,
        improvedFaqs: [],
        newSuggestions: [],
        qualityScore: 0,
        improvements: [],
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }
}

// ============================================================================
// CONVENIENCE EXPORTS
// ============================================================================

/**
 * Create FAQ generator instance
 */
export function createFAQGenerator(): FAQGeneratorService {
  return new FAQGeneratorService();
}

/**
 * Quick FAQ generation from text content
 */
export async function generateFAQsFromText(
  content: string,
  options?: Partial<GenerateFAQsOptions>
): Promise<FAQGenerationResult> {
  const generator = new FAQGeneratorService();
  return generator.generateFromDocument({
    documentContent: content,
    documentTitle: options?.documentTitle || 'Business Document',
    documentCategory: options?.documentCategory,
    businessType: options?.businessType,
    faqCount: options?.faqCount,
  });
}

export default FAQGeneratorService;
