/**
 * AI Prompt Library for FAQ Bank Pipeline
 *
 * Generates FAQ bank data in 3 stages using company context, ICP data,
 * and brand strategy as seed input. Follows the same pattern as website planner prompts.
 */

// ============================================
// TYPES
// ============================================

export interface FaqBankPipelineInputs {
  /**
   * The user's own brief from the "Generate with AI" popup or the AI Chat
   * generation flow — audience, topics, tone, goals and the chosen data
   * sources. Stated as the highest-priority instruction in the prompt.
   */
  customInstructions?: string;

  // Company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // ICP context
  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  // Brand strategy context (enrichment)
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // FAQ-specific context
  existingCategoryNames?: string[];
  faqCount?: number;
  faqTypeFocus?: string;

  // For regenerate: existing FAQ identity
  existingFaqTitles?: string[];

  // Language for generated content
  language?: string; // 'English', 'Hindi', 'Marathi' - default is 'English'
}

export type PartialFaqBankAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: FaqBankPipelineInputs): string {
  const parts: string[] = [];
  // The user's brief goes FIRST and is marked authoritative — it is the one
  // part of the context they typed themselves, so it must win over the derived
  // company/ICP/brand material below when the two disagree.
  if (inputs.customInstructions?.trim()) {
    parts.push(
      `USER BRIEF (highest priority — follow this over the general company context below):\n${inputs.customInstructions.trim()}\n`
    );
  }

  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Description: ${inputs.companyDescription}`);
  if (inputs.companyIndustry) parts.push(`Industry: ${inputs.companyIndustry}`);
  if (inputs.companyBusinessModel) parts.push(`Business Model: ${inputs.companyBusinessModel}`);
  if (inputs.companyTargetAudience) parts.push(`Target Audience: ${inputs.companyTargetAudience}`);
  if (inputs.companyPrimaryOffering) parts.push(`Primary Offering: ${inputs.companyPrimaryOffering}`);
  if (inputs.companyUsps?.length) parts.push(`Key USPs: ${inputs.companyUsps.join(', ')}`);

  if (inputs.icpName) {
    const icpParts: string[] = [];
    icpParts.push(`Ideal Customer: ${inputs.icpName}`);
    if (inputs.icpIndustry) icpParts.push(`Industry: ${inputs.icpIndustry}`);
    if (inputs.icpCompanySize) icpParts.push(`Size: ${inputs.icpCompanySize}`);
    if (inputs.icpPainPoints?.length) icpParts.push(`Pain Points: ${inputs.icpPainPoints.join(', ')}`);
    if (inputs.icpBusinessGoals?.length) icpParts.push(`Goals: ${inputs.icpBusinessGoals.join(', ')}`);
    parts.push(`\nICP Context:\n${icpParts.join('\n')}`);
  }

  if (inputs.brandArchetype || inputs.brandPositioning) {
    const brandParts: string[] = [];
    if (inputs.brandArchetype) brandParts.push(`Brand Archetype: ${inputs.brandArchetype}`);
    if (inputs.brandPersonality?.length) brandParts.push(`Brand Personality: ${inputs.brandPersonality.join(', ')}`);
    if (inputs.brandValues?.length) brandParts.push(`Brand Values: ${inputs.brandValues.join(', ')}`);
    if (inputs.brandPositioning) brandParts.push(`Brand Positioning: ${inputs.brandPositioning}`);
    if (inputs.brandVoice) brandParts.push(`Brand Voice: ${inputs.brandVoice}`);
    parts.push(`\nBrand Strategy:\n${brandParts.join('\n')}`);
  }

  if (inputs.existingCategoryNames?.length) {
    parts.push(`\nExisting FAQ Categories: ${inputs.existingCategoryNames.join(', ')}`);
  }
  if (inputs.faqCount) {
    parts.push(`Desired FAQ Count: ~${inputs.faqCount}`);
  }
  if (inputs.faqTypeFocus) {
    parts.push(`FAQ Type Focus: ${inputs.faqTypeFocus}`);
  }
  if (inputs.existingFaqTitles?.length) {
    parts.push(`\nExisting FAQ Titles (avoid duplicating these):\n${inputs.existingFaqTitles.join('\n')}`);
  }

  return parts.join('\n');
}

function buildLanguageInstruction(language?: string): string {
  if (!language || language.toLowerCase() === 'english') {
    return '';
  }
  const langLower = language.toLowerCase();
  if (langLower === 'hindi') {
    return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (categories, questions, answers, short answers, tags, meta titles, meta descriptions, keywords, strategy notes, AI usage notes, and any other text) entirely in Hindi using Devanagari script (हिंदी देवनागरी लिपि). Do NOT use English anywhere except for JSON field names. All text values must be natural, fluent Hindi appropriate for B2B FAQ contexts in India.`;
  }
  if (langLower === 'marathi') {
    return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (categories, questions, answers, short answers, tags, meta titles, meta descriptions, keywords, strategy notes, AI usage notes, and any other text) entirely in Marathi using Devanagari script (मराठी देवनागरी लिपि). Do NOT use English anywhere except for JSON field names. All text values must be natural, fluent Marathi appropriate for B2B FAQ contexts in Maharashtra, India.`;
  }
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content in ${language}. All text values (questions, answers, categories, tags, notes, etc.) must be in the specified language. Only JSON field names should remain in English.`;
}

const JSON_INSTRUCTION = '\n\nIMPORTANT: Respond with ONLY valid JSON. No markdown fences, no explanation before or after the JSON. Do not wrap in ```json``` blocks.';

// ============================================
// STAGE 1: FAQ STRATEGY & TOPIC DISCOVERY
// ============================================

export function buildFaqStrategyPrompt(inputs: FaqBankPipelineInputs): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const systemPrompt = `You are a B2B FAQ strategy AI. Given information about a company, their ideal customer profile, and brand identity, design a comprehensive FAQ strategy that addresses customer questions, reduces support burden, and improves SEO visibility.

Analyze the company's offerings, target audience pain points, and industry to determine the most impactful FAQ topics, categories, and approach.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "suggestedCategories": [
    {
      "name": "string — category name, e.g. 'Getting Started', 'Billing', 'Technical'",
      "description": "string — brief category description",
      "faqType": "string — one of: customer, sales, technical, internal, ai-training, website, blog, newsletter, support, onboarding, legal, hr, sop"
    }
  ],
  "targetAudienceProfile": "string — description of the primary audience for these FAQs, e.g. 'Mid-market SaaS decision makers evaluating our platform'",
  "faqStrategyNotes": "string — overall guidance on FAQ tone, approach, and priorities",
  "primaryTopics": ["array of 5-10 primary topics/questions these FAQs should address"],
  "searchIntentProfile": "string — overall search intent profile, e.g. 'Mix of informational and commercial investigation queries'"
}`;

  const userPrompt = `Design an FAQ strategy for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}

// ============================================
// STAGE 2: FAQ CONTENT GENERATION
// ============================================

export function buildFaqContentPrompt(inputs: FaqBankPipelineInputs, partial: PartialFaqBankAnalysis): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const priorContext = [];
  if (partial.targetAudienceProfile) priorContext.push(`Target Audience: ${partial.targetAudienceProfile}`);
  if (partial.faqStrategyNotes) priorContext.push(`Strategy Notes: ${partial.faqStrategyNotes}`);
  if (partial.primaryTopics) priorContext.push(`Primary Topics: ${Array.isArray(partial.primaryTopics) ? partial.primaryTopics.join(', ') : partial.primaryTopics}`);
  if (partial.searchIntentProfile) priorContext.push(`Search Intent: ${partial.searchIntentProfile}`);
  const categoryNames = Array.isArray(partial.suggestedCategories)
    ? partial.suggestedCategories.map((c: any) => c.name).join(', ')
    : '';
  if (categoryNames) priorContext.push(`Categories: ${categoryNames}`);
  const contextStr = priorContext.length > 0 ? `\n\nFAQ Strategy:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a B2B FAQ content AI. Based on the FAQ strategy, generate 5-10 specific FAQ items with complete questions and answers. Each answer should be thorough yet concise, optimized for both readability and SEO.

Generate FAQs that address real customer concerns, reduce support tickets, and rank well in search results. Match the brand voice and tone from the strategy.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "faqs": [
    {
      "title": "string — short title for the FAQ, e.g. 'How to Get Started'",
      "question": "string — the full question, e.g. 'How do I get started with your platform?'",
      "answer": "string — the complete answer, 2-4 sentences, informative and clear",
      "shortAnswer": "string — a 1-sentence summary answer, e.g. 'You can start with a free 14-day trial, no credit card required.'",
      "faqType": "string — one of: customer, sales, technical, internal, ai-training, website, blog, newsletter, support, onboarding, legal, hr, sop",
      "tags": ["array of 2-5 relevant tags"],
      "priority": "string — one of: low, medium, high, critical",
      "audienceType": "string — one of: public, internal, team-specific, department-specific, admin-only",
      "funnelStage": "string — one of: tofu, mofu, bofu, post-sale, general"
    }
  ],
  "faqClusterTopic": "string — the umbrella topic these FAQs fall under"
}`;

  const userPrompt = `Generate FAQ items for this business:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// STAGE 3: FAQ SEO & AI ENHANCEMENT
// ============================================

export function buildFaqSeoPrompt(inputs: FaqBankPipelineInputs, partial: PartialFaqBankAnalysis): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const faqCount = Array.isArray(partial.faqs) ? partial.faqs.length : 0;
  const faqTitles = Array.isArray(partial.faqs)
    ? partial.faqs.map((f: any) => f.question || f.title).join('\n')
    : '';

  const systemPrompt = `You are a B2B FAQ SEO and AI readiness AI. Based on the generated FAQs, enhance each one with SEO metadata and AI context fields. Ensure each FAQ is optimized for search engines and can be effectively used in AI-powered systems.${languageInstruction}

Provide SEO enhancements and AI usage notes for each of the ${faqCount} FAQs listed below.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "seoEnhancements": [
    {
      "metaTitle": "string — SEO meta title, 50-60 chars, e.g. 'How to Get Started | Company Name'",
      "metaDescription": "string — SEO meta description, 150-160 chars",
      "seoKeywords": ["array of 3-7 SEO keywords for this FAQ"],
      "searchIntent": "string — one of: informational, navigational, transactional, commercial"
    }
  ],
  "detailedAnswers": ["array of expanded answers (3-5 sentences each) for each FAQ, providing more depth"],
  "aiUsageNotes": [
    {
      "aiSuggestedUsage": "string — how this FAQ could be used in AI systems, e.g. 'Use as training data for customer support chatbot'",
      "aiPriority": "string — one of: low, medium, high, critical",
      "aiContextWeight": "number — 1-10, how important this FAQ is for AI context"
    }
  ],
  "relatedFaqTopics": ["array of 3-5 related FAQ topics that could be added later"]
}

The seoEnhancements, detailedAnswers, and aiUsageNotes arrays MUST each have exactly ${faqCount} items, one per FAQ in order.`;

  const userPrompt = `Enhance the following FAQs with SEO and AI readiness data:\n\nFAQs:\n${faqTitles}\n\nCompany context:\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 25000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildFaqBankEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a B2B FAQ strategy AI performing a refinement pass. The previous analysis for "${stageName}" had low confidence on certain fields. Please provide more specific, detailed, and well-reasoned analysis for the indicated fields.${JSON_INSTRUCTION}

Respond with the SAME JSON schema as before, but with improved values for the flagged fields. Keep the fields that already had good results unchanged.`;

  const userPrompt = `Previous analysis:\n${JSON.stringify(stageOutput, null, 2)}\n\nFields needing improvement (low confidence): ${lowConfidenceFields.join(', ')}\n\nPlease refine the analysis, providing more specific and detailed values for the flagged fields.`;

  return { systemPrompt, userPrompt, maxTokens: 15000 };
}