import { AIService } from './ai.service';

export interface GenerateDescriptionInput {
  title: string;
  subtitle?: string;
  author?: string;
  category?: string;
  language?: string;
  binding?: string;
  pageCount?: number;
  keywords?: string;
}

export interface GenerateSeoInput {
  title: string;
  author?: string;
  category?: string;
  description?: string;
}

export class AIGeneratorService {
  /**
   * AI Product Description, Synopsis & Marketing Copy Generator
   */
  static async generateProductDescription(input: GenerateDescriptionInput) {
    const prompt = `Generate comprehensive e-commerce product descriptions for this Indian book title:
Title: "${input.title}"
${input.subtitle ? `Subtitle: "${input.subtitle}"\n` : ''}${input.author ? `Author: "${input.author}"\n` : ''}${input.category ? `Category/Subject: "${input.category}"\n` : ''}${input.language ? `Language: "${input.language}"\n` : ''}${input.binding ? `Binding: "${input.binding}"\n` : ''}${input.pageCount ? `Pages: ${input.pageCount}\n` : ''}${input.keywords ? `Key Focus Areas: "${input.keywords}"\n` : ''}

Generate:
1. shortDescription: Catchy 2-3 sentence overview for product card previews.
2. detailedSynopsis: Rich 3-paragraph scholarly overview, historical context, and thematic significance.
3. keyHighlights: Array of 4-6 bullet points highlighting unique features (e.g. Sanskrit verse translation, commentary, archival binding).
4. tableOfContents: An illustrative outline/chapter breakdown.
5. marketingAdCopy: Persuasive promotional copy for email newsletters and social media.`;

    const schemaHint = `{
  "shortDescription": string,
  "detailedSynopsis": string,
  "keyHighlights": string[],
  "tableOfContents": string[],
  "marketingAdCopy": string
}`;

    if (AIService.isAIConfigured()) {
      try {
        return await AIService.generateJSON(
          prompt,
          'You are a distinguished scholar and senior e-commerce copywriter specializing in Indian literature, Vedic studies, Indology, and academic publications.',
          schemaHint
        );
      } catch (err: any) {
        console.warn('AI description generation failed, falling back to heuristic:', err.message);
      }
    }

    // Heuristic Fallback
    return {
      shortDescription: `An authoritative edition of "${input.title}"${input.author ? ` by ${input.author}` : ''}, presenting authentic insights into Indian philosophy, literature, and cultural heritage.`,
      detailedSynopsis: `"${input.title}" stands as an invaluable contribution to classical Indian thought and scholarship. Carefully curated for students, researchers, and dedicated readers, this edition delivers a faithful presentation of the foundational text alongside critical contextual notes and commentary.\n\nEncompassing profound philosophical inquiries, literary depth, and historical precision, this work explores essential Vedic and cultural tenets with clarity and reverence.\n\nPrinted on archival-quality paper with durable binding, this volume serves as an enduring reference for personal libraries and academic institutions worldwide.`,
      keyHighlights: [
        'Authoritative scholarly translation and comprehensive exegesis',
        'Detailed verse-by-verse commentary and philological notes',
        'Includes historical background, appendices, and index',
        'Premium archival binding designed for lifelong durability',
      ],
      tableOfContents: [
        'Introduction and Historical Context',
        'Section I: Philosophical Foundations and Core Principles',
        'Section II: Thematic Expositions and Critical Commentary',
        'Section III: Concluding Syntheses and Scholarly Epilogue',
        'Glossary of Terms, Sanskrit Lexicon, and Bibliography',
      ],
      marketingAdCopy: `Discover "${input.title}" — a must-have masterpiece for your Indian literature and philosophy collection. Worldwide shipping available from Indian Books Worldwide.`,
    };
  }

  /**
   * AI SEO & OpenGraph Metadata Generator
   */
  static async generateSeoMetadata(input: GenerateSeoInput) {
    const prompt = `Generate optimized SEO tags and OpenGraph metadata for the book "${input.title}" by ${input.author || 'Renowned Author'} in category "${input.category || 'Indian Literature'}".
Description context: ${input.description ? input.description.slice(0, 300) : 'Classical Indian literature and academic publication'}.

Generate:
1. metaTitle: Under 60 characters, high CTR, including primary search term.
2. metaDescription: Under 155 characters, engaging call-to-action.
3. focusKeywords: Array of 8-10 high-intent search terms.
4. ogTitle: Engaging social media title.
5. ogDescription: Engaging social media description.
6. canonicalSlug: Clean URL slug.`;

    const schemaHint = `{
  "metaTitle": string,
  "metaDescription": string,
  "focusKeywords": string[],
  "ogTitle": string,
  "ogDescription": string,
  "canonicalSlug": string
}`;

    if (AIService.isAIConfigured()) {
      try {
        return await AIService.generateJSON(
          prompt,
          'You are a senior SEO specialist for Indian books, Indology, and international e-commerce.',
          schemaHint
        );
      } catch (err: any) {
        console.warn('AI SEO generation failed, falling back:', err.message);
      }
    }

    const cleanTitle = input.title.replace(/[^a-zA-Z0-9\s]/g, '').trim();
    const slug = cleanTitle.toLowerCase().replace(/\s+/g, '-');

    return {
      metaTitle: `Buy ${input.title} Online | Indian Books Worldwide`,
      metaDescription: `Order ${input.title}${input.author ? ` by ${input.author}` : ''} online at best price. Authentic editions, fast insured dispatch & worldwide delivery.`,
      focusKeywords: [
        input.title.toLowerCase(),
        `${input.title.toLowerCase()} book`,
        input.author ? `${input.author.toLowerCase()} books` : 'indian literature',
        'buy indian books online',
        'sanskrit books',
        'vedic scriptures',
        'indian philosophy books',
      ],
      ogTitle: `${input.title} - Authentic Edition | Indian Books Worldwide`,
      ogDescription: `Explore ${input.title} with complete critical commentary and worldwide insured delivery from Indian Books Worldwide.`,
      canonicalSlug: slug,
    };
  }

  /**
   * AI Keywords, Search Terms & Tags Generator
   */
  static async generateKeywordsAndTags(input: { title: string; description?: string; category?: string }) {
    const prompt = `Extract targeted keywords, search terms, and tags for:
Title: "${input.title}"
Category: "${input.category || 'General'}"
Description: "${input.description?.slice(0, 300) || ''}"

Return JSON with "keywords" (string array of 12-15 terms), "searchPhrases" (string array of 5 long-tail query phrases), and "tags" (string array of 6-8 taxonomy tags).`;

    const schemaHint = `{
  "keywords": string[],
  "searchPhrases": string[],
  "tags": string[]
}`;

    if (AIService.isAIConfigured()) {
      try {
        return await AIService.generateJSON(
          prompt,
          'You are an expert e-commerce catalog taxonomist for Indian literature.',
          schemaHint
        );
      } catch (err: any) {
        console.warn('AI keyword generation failed, using fallback:', err.message);
      }
    }

    const words = input.title.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
    return {
      keywords: [
        ...words,
        'indian literature',
        'sanskrit texts',
        'vedic studies',
        'hindu philosophy',
        'indology',
        'critical edition',
        'hardcover book',
      ],
      searchPhrases: [
        `buy ${input.title.toLowerCase()} online`,
        `${input.title.toLowerCase()} best edition`,
        `${input.title.toLowerCase()} english translation`,
        `indian books on ${input.category?.toLowerCase() || 'philosophy'}`,
      ],
      tags: [
        input.category || 'Literature',
        'Vedic Literature',
        'Philosophy',
        'Sacred Texts',
        'Classical India',
      ],
    };
  }

  /**
   * AI FAQ Generator (from Product Details & Reader Inquiries)
   */
  static async generateFaqs(input: { title: string; author?: string; binding?: string; description?: string; price?: number }) {
    const prompt = `Generate a structured list of 5 frequently asked customer questions (FAQs) and detailed, helpful answers for this book:
Title: "${input.title}"
Author: "${input.author || 'Indian Scholar'}"
Binding: "${input.binding || 'Hardcover'}"
Price: "₹${input.price || 500}"
Description: "${input.description?.slice(0, 300) || ''}"

Questions should address translation accuracy, original script (Devanagari/Sanskrit), packaging quality, delivery timelines, and suitability for beginners vs scholars.`;

    const schemaHint = `{
  "faqs": [
    { "question": string, "answer": string }
  ]
}`;

    if (AIService.isAIConfigured()) {
      try {
        return await AIService.generateJSON(
          prompt,
          'You are a helpful and knowledgeable bookstore customer service specialist.',
          schemaHint
        );
      } catch (err: any) {
        console.warn('AI FAQ generation failed, using fallback:', err.message);
      }
    }

    return {
      faqs: [
        {
          question: `Does this edition of "${input.title}" contain original Sanskrit/Hindi text alongside translation?`,
          answer: `Yes, this authentic edition includes original shlokas/verses accompanied by precise transliteration and comprehensive commentary.`,
        },
        {
          question: `Is "${input.title}" suitable for both beginners and advanced scholars?`,
          answer: `The text is structured with an accessible introductory guide for new readers, while the detailed footnotes and critical apparatus cater to academic scholars.`,
        },
        {
          question: `What packaging is used for shipping fragile books and multi-volume sets?`,
          answer: `All consignments are packed with multi-layer bubble wrap and moisture-resistant archival sleeves to ensure pristine delivery across India and worldwide.`,
        },
        {
          question: `What is the estimated delivery timeframe for domestic and international orders?`,
          answer: `Orders within India are delivered within 2-5 business days via express courier. International air shipments reach most destinations within 4-8 business days.`,
        },
        {
          question: `Can I get digital or eBook versions of this title?`,
          answer: `When available, eBook editions (PDF/EPUB) can be purchased on the product page for instant digital download.`,
        },
      ],
    };
  }

  /**
   * AI Auto Tag & Topic Classifier
   */
  static async generateAutoTags(input: { title: string; description?: string }) {
    const prompt = `Classify this book into standard library and bookstore taxonomy:
Title: "${input.title}"
Description: "${input.description?.slice(0, 200) || ''}"

Generate:
1. primaryCategory (e.g. "Advaita Vedanta", "Ayurveda", "Epic Poetry")
2. genres (array of 3-4 genres)
3. targetAudience (e.g. "Scholars, University Students, Spiritual Seekers")
4. era (e.g. "Vedic Period", "Classical Sanskrit", "Medieval Bhakti", "Modern Indology")`;

    const schemaHint = `{
  "primaryCategory": string,
  "genres": string[],
  "targetAudience": string,
  "era": string
}`;

    if (AIService.isAIConfigured()) {
      try {
        return await AIService.generateJSON(
          prompt,
          'You are a library science and Indology cataloguing specialist.',
          schemaHint
        );
      } catch (err: any) {
        console.warn('AI Tag classification failed, using fallback:', err.message);
      }
    }

    return {
      primaryCategory: 'Classical Indian Literature',
      genres: ['Philosophy', 'Scripture', 'Commentary', 'Cultural Studies'],
      targetAudience: 'Scholars, Researchers & General Readers',
      era: 'Classical Sanskrit & Vedic Tradition',
    };
  }
}
