/**
 * AI Prompt Library for Testimonial Pipeline
 *
 * Generates testimonial data in 3 stages using company context, ICP data,
 * and brand strategy as seed input. Produces 5-6 diverse testimonials per run.
 */

// ============================================
// TYPES
// ============================================

export interface TestimonialPipelineInputs {
  /**
   * 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;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  // Brand strategy context (enrichment)
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // Testimonial specific
  testimonialType?: string;
  testimonialCategory?: string;

  // Number of testimonials to generate (default: 5)
  targetCount?: number;

  // For regenerate: existing testimonial identity
  existingCustomerName?: string;
  existingType?: string;
  existingHeadline?: string;

  // Language for generated content
  language?: string; // 'English', 'Hindi', 'Marathi' - default is 'English'
}

export type PartialTestimonialAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

const DIVERSITY_HINTS = [
  'Focus on ROI and measurable business outcomes (e.g., cost savings, revenue growth, efficiency gains).',
  'Focus on customer experience and service quality (e.g., support responsiveness, ease of use, onboarding).',
  'Focus on implementation and technical excellence (e.g., fast deployment, integration, performance).',
  'Focus on strategic impact and leadership perspective (e.g., competitive advantage, market positioning).',
  'Focus on emotional transformation and personal impact (e.g., reduced stress, confidence, work-life balance).',
  'Focus on partnership and long-term value (e.g., ongoing innovation, scalability, reliability).',
];

function buildCompanyContext(inputs: TestimonialPipelineInputs): 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.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.testimonialType) parts.push(`Testimonial Type Focus: ${inputs.testimonialType}`);
  if (inputs.testimonialCategory) parts.push(`Testimonial Category Focus: ${inputs.testimonialCategory}`);

  if (inputs.existingCustomerName) {
    parts.push(`\nRegenerating testimonial for: ${inputs.existingCustomerName}`);
    if (inputs.existingType) parts.push(`Existing type: ${inputs.existingType}`);
    if (inputs.existingHeadline) parts.push(`Existing headline: ${inputs.existingHeadline}`);
    parts.push(`Keep the customer identity. Refresh and improve all other data.`);
  }

  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 (customer names, company names, headlines, quotes, full testimonials, stories, key results, emotional highlights, before/during/after states, challenges, solutions, 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 testimonial contexts in India.';
  }
  if (langLower === 'marathi') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (customer names, company names, headlines, quotes, full testimonials, stories, key results, emotional highlights, before/during/after states, challenges, solutions, 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 testimonial contexts in Maharashtra, India.';
  }
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content in ${language}. All text values (customer names, headlines, quotes, testimonials, stories, 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: TESTIMONIAL IDENTITY & CUSTOMER PROFILE (ARRAY)
// ============================================

export function buildTestimonialIdentityPrompt(inputs: TestimonialPipelineInputs, targetCount?: number): PromptResult {
  const count = targetCount || inputs.targetCount || 5;
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const existingInstruction = inputs.existingCustomerName
    ? ` You MUST keep the customer name as "${inputs.existingCustomerName}" and regenerate around that identity.`
    : '';

  const diversityList = DIVERSITY_HINTS.slice(0, count).map((hint, i) =>
    `- Testimonial ${i + 1}: ${hint}`
  ).join('\n');

  const systemPrompt = `You are a B2B testimonial strategy AI. Given information about a company, their ideal customer profile, and brand identity, generate ${count} diverse, realistic testimonials from different satisfied customer perspectives.

Each testimonial must feel authentic and specific, avoiding generic marketing language. They should reflect different typical experiences of the company's ideal customers.
${languageInstruction}

Diversity guidelines — each testimonial should cover a different angle:
${diversityList}${existingInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "testimonials": [
    {
      "customerName": "string — realistic customer name, e.g. 'Sarah Chen'",
      "customerCompany": "string — realistic company name, e.g. 'TechVentures Inc'",
      "customerDesignation": "string — job title, e.g. 'VP of Engineering'",
      "customerIndustry": "string — industry, e.g. 'Technology'",
      "customerLocation": "string — location, e.g. 'San Francisco, CA'",
      "type": "string — one of: text, video, audio, case-study, social-media, review, interview, before-after, quote, story",
      "category": "string — one of: product-quality, customer-service, value-for-money, ease-of-use, implementation, trust-security, results-roi, partnership, problem-solved, user-experience, industry-expertise, integration",
      "headline": "string — attention-grabbing headline",
      "authorityLevel": "string — one of: executive, manager, specialist, individual",
      "detailDepth": "string — one of: brief, moderate, detailed, comprehensive"
    }
  ]
}

Generate exactly ${count} testimonials. Each must have a UNIQUE customer name, company, industry, and perspective.`;

  const userPrompt = `Generate ${count} diverse testimonial identities for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 3000 };
}

// ============================================
// STAGE 2: TESTIMONIAL CONTENT & NARRATIVE (ARRAY)
// ============================================

export function buildTestimonialContentPrompt(inputs: TestimonialPipelineInputs, partials: PartialTestimonialAnalysis[]): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const identitiesList = partials.map((p, i) => {
    const parts: string[] = [];
    if (p.customerName) parts.push(`Customer: ${p.customerName}`);
    if (p.customerCompany) parts.push(`Company: ${p.customerCompany}`);
    if (p.customerDesignation) parts.push(`Role: ${p.customerDesignation}`);
    if (p.headline) parts.push(`Headline: ${p.headline}`);
    if (p.type) parts.push(`Type: ${p.type}`);
    if (p.category) parts.push(`Category: ${p.category}`);
    return `Testimonial ${i + 1}:\n${parts.join('\n')}`;
  }).join('\n\n');
  const contextStr = identitiesList ? `\n\nTestimonial Identities:\n${identitiesList}` : '';

  const systemPrompt = `You are a B2B testimonial content writer AI. Based on the ${partials.length} testimonial identities provided, generate authentic, compelling testimonial content for EACH one. Write in first person from each customer's perspective. Include specific details, emotions, and measurable outcomes.

Each testimonial must tell a DIFFERENT story with DIFFERENT challenges, solutions, and results. Avoid overly promotional language — it should feel like real people sharing their experiences.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "testimonials": [
    {
      "shortQuote": "string — powerful 1-2 sentence quote, max 300 chars",
      "fullTestimonial": "string — complete testimonial, 3-5 paragraphs. Problem to solution to results.",
      "story": "string — narrative story version, 4-6 paragraphs with vivid before/after contrast",
      "keyResults": ["array of 4-6 specific, measurable results"],
      "emotionalHighlight": "string — the emotional core of the testimonial",
      "beforeState": "string — situation before using the product, 2-3 sentences",
      "duringState": "string — implementation/transition experience, 2-3 sentences",
      "afterState": "string — results after implementation, 2-3 sentences",
      "challenge": "string — main challenge or pain point",
      "solution": "string — how the product/service addressed the challenge",
      "results": "string — tangible outcomes and impact achieved"
    }
  ]
}

Generate exactly ${partials.length} testimonial content objects. The array order must match the identity order.`;

  const userPrompt = `Generate content for ${partials.length} testimonials:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 5000 };
}

// ============================================
// STAGE 3: TESTIMONIAL QUALITY & CONTEXT (ARRAY)
// ============================================

export function buildTestimonialQualityPrompt(inputs: TestimonialPipelineInputs, partials: PartialTestimonialAnalysis[]): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const contextList = partials.map((p, i) => {
    const parts: string[] = [];
    if (p.customerName) parts.push(`Customer: ${p.customerName}`);
    if (p.headline) parts.push(`Headline: ${p.headline}`);
    if (p.shortQuote) parts.push(`Quote: ${String(p.shortQuote).substring(0, 150)}...`);
    if (p.type) parts.push(`Type: ${p.type}`);
    return `Testimonial ${i + 1}:\n${parts.join('\n')}`;
  }).join('\n\n');
  const contextStr = contextList ? `\n\nTestimonial Contexts:\n${contextList}` : '';

  const systemPrompt = `You are a B2B testimonial quality and context AI. Based on the ${partials.length} testimonials provided, assign quality scores, generate ROI metrics, and add contextual tags for EACH testimonial.

Quality scores should be realistic — not every testimonial should score 90+. Vary the scores across testimonials.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "testimonials": [
    {
      "roiMetrics": [
        {
          "metric": "string — metric name, e.g. 'Time Saved Per Week'",
          "value": "string — the value, e.g. '15 hours'",
          "unit": "string — measurement unit, e.g. 'hours', '%', '$'"
        }
      ],
      "authenticityScore": "number — 0-100",
      "emotionalImpactScore": "number — 0-100",
      "conversionPotential": "number — 0-100",
      "specificityScore": "number — 0-100",
      "trustScore": "number — 0-100",
      "campaignTags": ["array of 2-4 campaign tags"],
      "industryTags": ["array of 2-4 industry tags"],
      "audienceTags": ["array of 2-4 audience tags"],
      "collectionMethod": "string — one of: form, email, interview, imported",
      "language": "string — language code, e.g. 'en'"
    }
  ]
}

Generate exactly ${partials.length} quality/context objects. The array order must match the testimonial order.`;

  const userPrompt = `Generate quality scores and contextual metadata for ${partials.length} testimonials:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 4000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildTestimonialEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a B2B testimonial AI performing a refinement pass on a testimonial. 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: 1500 };
}