/**
 * AI Prompt Library for Case Study Pipeline
 *
 * Generates case study 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 CaseStudyPipelineInputs {
  /**
   * 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;

  // Case study specific
  industryFocus?: string;
  departmentFocus?: string;

  // Custom user description for targeted generation
  customDescription?: string;

  // Number of case studies to generate (default: 4)
  targetCount?: number;

  // For regenerate: existing case study identity
  existingTitle?: string;
  existingIndustry?: string;
  existingDepartment?: string;

  // Language for generated content
  language?: string; // 'English', 'Hindi', 'Marathi' - default is 'English'
}

export type PartialCaseStudyAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: CaseStudyPipelineInputs): 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.industryFocus) parts.push(`Industry Focus: ${inputs.industryFocus}`);
  if (inputs.departmentFocus) parts.push(`Department Focus: ${inputs.departmentFocus}`);

  // Custom user description for targeted generation
  if (inputs.customDescription) {
    parts.push(`\nCUSTOM GENERATION REQUEST:\n${inputs.customDescription}\n\nIMPORTANT: Generate case studies that specifically address the above requirements. Focus on the industries, challenges, solutions, and outcomes mentioned.`);
  }

  if (inputs.existingTitle) {
    parts.push(`\nRegenerating case study: ${inputs.existingTitle}`);
    if (inputs.existingIndustry) parts.push(`Existing industry: ${inputs.existingIndustry}`);
    if (inputs.existingDepartment) parts.push(`Existing department: ${inputs.existingDepartment}`);
    parts.push(`Keep the title and 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 (titles, descriptions, executive summaries, challenges, goals, solutions, strategies, execution steps, results, key takeaways, KPI labels, testimonials, SEO metadata, 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 case study contexts in India.';
  }
  if (langLower === 'marathi') {
    return '\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (titles, descriptions, executive summaries, challenges, goals, solutions, strategies, execution steps, results, key takeaways, KPI labels, testimonials, SEO metadata, 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 case study contexts in Maharashtra, India.';
  }
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content in ${language}. All text values (titles, descriptions, challenges, solutions, results, 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: CASE STUDY FOUNDATION & CLIENT CONTEXT
// ============================================

const DIVERSITY_HINTS = [
  'Focus on revenue growth and sales acceleration outcomes.',
  'Focus on operational efficiency and cost reduction outcomes.',
  'Focus on customer success and satisfaction improvements.',
  'Focus on product adoption and user engagement outcomes.',
];

export function buildCaseStudyFoundationPrompt(inputs: CaseStudyPipelineInputs, targetCount?: number): PromptResult {
  const count = targetCount || inputs.targetCount || 1;
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const existingInstruction = inputs.existingTitle
    ? ` You MUST keep the case study title as "${inputs.existingTitle}" and regenerate around that identity.`
    : '';

  const systemPrompt = `You are a B2B case study strategy AI. Given information about a company, their ideal customer profile, and brand identity, generate ${count} diverse case study foundations that showcase how the company helps clients achieve measurable results.

Each case study should follow the challenge-solution-results framework and be tailored to the target audience. The ${count} case studies MUST be meaningfully different from each other — different client industries, departments, pain points, and outcome types.

Diversity guidelines:
- Case study 1: ${DIVERSITY_HINTS[0]}
- Case study 2: ${DIVERSITY_HINTS[1]}
- Case study 3: ${DIVERSITY_HINTS[2]}
- Case study 4: ${DIVERSITY_HINTS[3]}${existingInstruction}${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "caseStudies": [
    {
      "title": "string — compelling case study title",
      "slug": "string — URL-friendly slug",
      "shortDescription": "string — 1-2 sentence summary",
      "clientName": "string — fictional client company name",
      "clientIndustry": "string — one of: technology, healthcare, finance, education, retail, manufacturing, media, hospitality, real-estate, logistics, other",
      "clientWebsite": "string — fictional client website",
      "department": "string — one of: marketing, sales, engineering, product, design, hr, finance, operations, customer-success, leadership, other",
      "industry": "string — one of: technology, healthcare, finance, education, retail, manufacturing, media, hospitality, real-estate, logistics, other",
      "tags": ["array of 3-6 relevant tags"],
      "servicesUsed": ["array of 2-4 services"],
      "productsUsed": ["array of 1-3 products"],
      "priority": "string — one of: low, medium, high, critical",
      "visibility": "string — one of: public, private, internal"
    }
  ]
}

Generate exactly ${count} case studies. Each must have a unique client name, industry, and department.`;

  const userPrompt = `Generate ${count} diverse case study foundations for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// STAGE 2: CASE STUDY CONTENT & NARRATIVE
// ============================================

export function buildCaseStudyContentPrompt(inputs: CaseStudyPipelineInputs, partials: PartialCaseStudyAnalysis[]): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const foundationsList = partials.map((p, i) => {
    const parts: string[] = [];
    if (p.title) parts.push(`Title: ${p.title}`);
    if (p.clientName) parts.push(`Client: ${p.clientName}`);
    if (p.industry) parts.push(`Industry: ${p.industry}`);
    if (p.department) parts.push(`Department: ${p.department}`);
    if (p.shortDescription) parts.push(`Summary: ${p.shortDescription}`);
    return `Case Study ${i + 1}:\n${parts.join('\n')}`;
  }).join('\n\n');
  const contextStr = foundationsList ? `\n\nCase Study Foundations:\n${foundationsList}` : '';

  const systemPrompt = `You are a B2B case study content writer AI. Based on the ${partials.length} case study foundations provided, generate detailed, compelling narratives for EACH case study that follows the challenge-solution-results framework. Write in a professional, results-focused tone that highlights measurable outcomes.

The content for each case study should be specific, data-driven, and include concrete details rather than vague claims. Each case study must have DIFFERENT challenges, solutions, and results.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "caseStudies": [
    {
      "detailedDescription": "string — full case study description, 3-5 paragraphs",
      "executiveSummary": "string — 2-3 sentence executive summary",
      "challenge": "string — detailed challenge description, 2-3 paragraphs with specific pain points",
      "goals": "string — 3-5 specific, measurable goals",
      "solution": "string — detailed solution description, 2-3 paragraphs",
      "strategy": "string — strategic approach, 1-2 paragraphs",
      "executionSteps": "string — key implementation steps",
      "results": "string — detailed results, 2-3 paragraphs with specific numbers",
      "keyTakeaways": ["array of 3-5 key takeaways"]
    }
  ]
}

Generate exactly ${partials.length} case study content objects. The array order must match the foundation order.`;

  const userPrompt = `Generate content for ${partials.length} case studies:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 50000 };
}

// ============================================
// STAGE 3: CASE STUDY KPIs & SEO
// ============================================

export function buildCaseStudyKpisSeoPrompt(inputs: CaseStudyPipelineInputs, partials: PartialCaseStudyAnalysis[]): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);
  const contextList = partials.map((p, i) => {
    const parts: string[] = [];
    if (p.title) parts.push(`Title: ${p.title}`);
    if (p.clientName) parts.push(`Client: ${p.clientName}`);
    if (p.challenge) parts.push(`Challenge: ${String(p.challenge).substring(0, 200)}...`);
    if (p.solution) parts.push(`Solution: ${String(p.solution).substring(0, 200)}...`);
    return `Case Study ${i + 1}:\n${parts.join('\n')}`;
  }).join('\n\n');
  const contextStr = contextList ? `\n\nCase Study Contexts:\n${contextList}` : '';

  const systemPrompt = `You are a B2B case study metrics and SEO AI. Based on the ${partials.length} case studies provided, generate realistic KPI metrics, implementation workflow steps, before/after descriptions, SEO metadata, and client testimonials for EACH case study.

Make all metrics realistic and specific. Numbers should reflect typical B2B SaaS improvement ranges. Each case study must have DIFFERENT KPIs and metrics.${languageInstruction}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "caseStudies": [
    {
      "kpis": [
        {
          "label": "string — KPI name",
          "value": "string — the after value",
          "beforeValue": "string — the before value",
          "afterValue": "string — the after value",
          "unit": "string — measurement unit",
          "changePercent": "number — percentage change"
        }
      ],
      "steps": [
        {
          "title": "string — step title",
          "description": "string — brief description",
          "order": "number — step order",
          "type": "string — one of: challenge, strategy, execution, result, note"
        }
      ],
      "beforeDescription": "string — before implementation state, 2-3 sentences",
      "afterDescription": "string — after implementation state, 2-3 sentences",
      "beforeMetrics": ["array of 3-4 before-state metrics"],
      "afterMetrics": ["array of 3-4 after-state metrics"],
      "metaTitle": "string — SEO meta title, 50-60 chars",
      "metaDescription": "string — SEO meta description, 150-160 chars",
      "seoKeywords": ["array of 5-8 SEO keywords"],
      "testimonials": [
        {
          "quote": "string — client testimonial quote, 1-2 sentences",
          "author": "string — author name",
          "role": "string — author role",
          "company": "string — author company"
        }
      ]
    }
  ]
}

Generate exactly ${partials.length} case study KPI/SEO objects. The array order must match the case study order.`;

  const userPrompt = `Generate KPIs, workflow steps, and SEO metadata for ${partials.length} case studies:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 50000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildCaseStudyEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a B2B case study AI performing a refinement pass on a case study. 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 };
}