/**
 * AI Prompt Library for Blog Pipeline
 *
 * Generates blog content strategy, titles, and SEO enhancements
 * in 3 stages using company context, ICP data, and brand strategy.
 */

// ============================================
// TYPES
// ============================================

export interface BlogPipelineInputs {
  // Company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyTargetGeography?: string;
  companyCountry?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // ICP context
  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpLocation?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  // Brand strategy context
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // Blog-specific context
  existingBlogTitles?: string[];
  targetBlogCount?: number;
  contentDepthPreference?: string;

  /**
   * The user's own brief from the "Generate with AI" popup (or the AI-Chat blog
   * flow) — audience, topics, tone, goals, and the chosen data sources.
   *
   * The route used to drop this: `/auto-fill` never read `customInstructions`
   * off the body, so the required Prompt field was collected and then ignored,
   * and every generation came out of company context alone. It is threaded
   * through here and stated as the highest-priority instruction below.
   */
  customInstructions?: string;

  // Language for content generation (ISO 639-1 code, e.g. 'en', 'hi', 'mr')
  language?: string;

  // Scheduling context
  startDate?: string;
  endDate?: string;
  frequency?: string;
  numberOfPosts?: number;
}

export type PartialBlogAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: BlogPipelineInputs): string {
  const parts: string[] = [];
  // The user's brief goes FIRST and is marked as authoritative — it is the one
  // part of the context they typed themselves, so it must win over the derived
  // company/ICP/brand material that follows 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.companyTargetGeography) parts.push(`Target Geography: ${inputs.companyTargetGeography}`);
  if (inputs.companyCountry) parts.push(`Country: ${inputs.companyCountry}`);
  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.icpLocation) icpParts.push(`Location: ${inputs.icpLocation}`);
    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.existingBlogTitles?.length) {
    parts.push(`\nExisting Blog Titles (avoid duplicating these):\n${inputs.existingBlogTitles.join('\n')}`);
  }
  if (inputs.targetBlogCount) {
    parts.push(`Target Blog Count: ~${inputs.targetBlogCount}`);
  } else {
    parts.push('Target Blog Count: ~5');
  }
  if (inputs.contentDepthPreference) {
    parts.push(`Content Depth Preference: ${inputs.contentDepthPreference}`);
  }

  // Scheduling context
  if (inputs.startDate && inputs.endDate) {
    const freqLabel = inputs.frequency === 'daily' ? 'daily' : inputs.frequency === 'weekly' ? 'weekly' : inputs.frequency === 'bi-weekly' ? 'bi-weekly' : inputs.frequency === 'monthly' ? 'monthly' : 'weekly';
    parts.push(`\nSCHEDULING CONSTRAINTS:
- Start Date: ${inputs.startDate}
- End Date: ${inputs.endDate}
- Frequency: ${freqLabel}
- Number of Posts: ${inputs.numberOfPosts || inputs.targetBlogCount || 5}
Distribute the blog posts evenly across the date range according to the selected frequency. Each post should have a suggested publish date within the range.`);
  }

  return parts.join('\n');
}

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.';

// ============================================
// LANGUAGE INSTRUCTION BUILDER
// ============================================

const LANGUAGE_NAMES: Record<string, string> = {
  'hi': 'Hindi using Devanagari script (हिंदी देवनागरी लिपि)',
  'mr': 'Marathi using Devanagari script (मराठी देवनागरी लिपि)',
};

function buildLanguageInstruction(language?: string): string {
  if (!language || language === 'en') return ''; // English is default, no instruction needed

  const languageName = LANGUAGE_NAMES[language] || language;
  return `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (strategy name, goals, target audience, titles, descriptions, excerpts, SEO metadata, content outlines, heading suggestions, briefs, and all other text) entirely in ${languageName}. Do NOT use English unless it is a technical term or proper noun. All text must be natural, fluent, and appropriate for B2B business contexts in the specified language.`;
}

function getLanguageLabel(language?: string): string {
  if (!language || language === 'en') return 'English';
  const names: Record<string, string> = {
    'hi': 'Hindi',
    'mr': 'Marathi',
  };
  return names[language] || language;
}

// ============================================
// STAGE 1: BLOG STRATEGY + SEO CONFIG
// ============================================

export function buildBlogStrategyPrompt(inputs: BlogPipelineInputs): PromptResult {
  const languageLabel = getLanguageLabel(inputs.language);
  const languageInstruction = buildLanguageInstruction(inputs.language);

  const systemPrompt = `You are a B2B content strategy AI. Given information about a company, their ideal customer profile, and brand identity, design a comprehensive blog content strategy with SEO configuration and content type allocations.

Create a strategy that drives organic traffic, establishes thought leadership, and converts readers through strategic content planning.

CRITICAL: The targetAudience and targetRegion fields MUST be derived from the company context provided — they should reflect the actual company's ICP, industry, geographic market, and customer profile. Never default to generic values like "Global" or "B2B decision-makers" unless the context genuinely supports them. Different companies in different industries and regions MUST produce different targetAudience and targetRegion values.${JSON_INSTRUCTION}${languageInstruction}

Your response must match this exact JSON schema:
{
  "blogStrategy": {
    "name": "string — strategy name, e.g. 'AI-First Content Strategy for [Company]'",
    "goals": ["array of goals from: seo, brand-awareness, lead-generation, product-education, authority-building, traffic-growth, conversion, community-building"],
    "targetAudience": "string — SPECIFIC target audience derived from the company's ICP, industry, and offerings. Must reflect the company's actual customer profile — include role, seniority, company type, and region-specific needs. Do NOT use generic descriptions like 'B2B decision-makers'. Match the granularity of the company's ICP and target audience context provided above.",
    "targetRegion": "string — SPECIFIC geographic region derived from the company's target geography, country, and ICP location. Use the company's actual market geography (e.g. 'India & South Asia', 'UK & Europe', 'North America', 'Middle East & GCC'). Only use 'Global' if the company genuinely operates worldwide. Match the company's stated target geography context above.",
    "language": "string — must be '${languageLabel}'",
    "funnelStage": "string — one of: tofu, mofu, bofu",
    "competitorBlogs": ["array of 3-5 competitor blog URLs or names for reference"],
    "contentDepth": "string — one of: brief, standard, deep, comprehensive",
    "creativityLevel": "number — 1-10, how creative vs data-driven the content should be"
  },
  "seoConfig": {
    "seoName": "string — name for this SEO configuration, e.g. 'Organic Growth SEO'",
    "searchIntent": "string — one of: informational, commercial, transactional, navigational",
    "targetAudience": "string — SEO-specific target audience derived from the company's ICP and industry. Must be specific (e.g. 'SaaS VPs of Marketing in mid-market companies' not 'B2B decision-makers'). Reflect the actual customer profile from the context above.",
    "primaryGoal": "string — one of: traffic, rankings, leads, authority",
    "primaryKeywords": ["array of 5-10 primary keywords"],
    "secondaryKeywords": ["array of 10-15 secondary keywords"],
    "longTailKeywords": ["array of 10-20 long-tail keyword phrases"],
    "negativeKeywords": ["array of 5-10 negative keywords to avoid"],
    "metaTitleTemplate": "string — e.g. '{{title}} | {{companyName}}'",
    "metaDescriptionTemplate": "string — e.g. '{{excerpt}}'",
    "titleMaxLength": "number — max meta title length, typically 60",
    "descriptionMaxLength": "number — max meta description length, typically 160",
    "minWordCount": "number — minimum word count per post, typically 3000",
    "maxWordCount": "number — maximum word count per post, typically 15000",
    "keywordDensityTarget": "number — target keyword density percentage, typically 1.5-2.5",
    "includeTOC": "boolean — whether to include table of contents",
    "includeConclusion": "boolean — whether to include conclusion section",
    "includeCTA": "boolean — whether to include call-to-action sections",
    "maxLinksPerPost": "number — maximum internal links per post, typically 5"
  },
  "contentTypes": [
    {
      "name": "string — content type name, e.g. 'How-To Guides'",
      "type": "string — one of: educational, how-to-guide, industry-trends, case-study, comparison, product-focused, listicle, problem-solution, thought-leadership, news-analysis, interview, tutorial, opinion, roundup, faq-style",
      "enabled": "boolean — whether this content type is active",
      "percentageAllocation": "number — % of content budget, 1-100",
      "priority": "number — priority order, 1=highest",
      "seoIntent": "string — one of: informational, commercial, transactional, navigational",
      "recommendedLength": "number — recommended word count for this type",
      "funnelPosition": "string — one of: tofu, mofu, bofu",
      "ctaStrategy": "string — call-to-action approach for this type",
      "conversionGoal": "string — what conversion this content type targets"
    }
  ],
  "blogStrategyNotes": "string — overall strategy notes and recommendations",
  "primaryTopics": ["array of 8-12 primary content topics to cover"]
}`;

  const userPrompt = `Design a blog content strategy for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 80000 };
}

// ============================================
// STAGE 2: BLOG TITLES GENERATION
// ============================================

export function buildBlogTitlesPrompt(inputs: BlogPipelineInputs, partial: PartialBlogAnalysis): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);

  const priorContext = [];
  if (partial.blogStrategy) {
    const bs = partial.blogStrategy;
    if (bs.name) priorContext.push(`Strategy: ${bs.name}`);
    if (bs.goals?.length) priorContext.push(`Goals: ${bs.goals.join(', ')}`);
    if (bs.targetAudience) priorContext.push(`Target Audience: ${bs.targetAudience}`);
    if (bs.contentDepth) priorContext.push(`Content Depth: ${bs.contentDepth}`);
    if (bs.creativityLevel) priorContext.push(`Creativity Level: ${bs.creativityLevel}/10`);
    if (bs.funnelStage) priorContext.push(`Funnel Stage: ${bs.funnelStage}`);
  }
  if (partial.seoConfig) {
    const sc = partial.seoConfig;
    if (sc.primaryKeywords?.length) priorContext.push(`Primary Keywords: ${sc.primaryKeywords.join(', ')}`);
    if (sc.secondaryKeywords?.length) priorContext.push(`Secondary Keywords: ${sc.secondaryKeywords.join(', ')}`);
    if (sc.searchIntent) priorContext.push(`Search Intent: ${sc.searchIntent}`);
  }
  if (partial.primaryTopics?.length) priorContext.push(`Primary Topics: ${partial.primaryTopics.join(', ')}`);
  if (partial.contentTypes?.length) {
    const typeNames = partial.contentTypes.map((ct: any) => `${ct.name} (${ct.type}, ${ct.funnelPosition})`).join(', ');
    priorContext.push(`Content Types: ${typeNames}`);
  }
  if (partial.blogStrategyNotes) priorContext.push(`Strategy Notes: ${partial.blogStrategyNotes}`);

  const blogCount = inputs.targetBlogCount || 5;
  const contextStr = priorContext.length > 0 ? `\n\nBlog Strategy:\n${priorContext.join('\n')}` : '';

  const systemPrompt = `You are a B2B SEO content strategist. Based on the blog strategy, generate ${blogCount} unique, SEO-optimized blog title ideas. Each title should be compelling, keyword-rich, and aligned with the content strategy.

Make titles that are specific, actionable, and unique. Avoid generic titles. Each title must target a distinct topic — no two titles should cover the same angle.${JSON_INSTRUCTION}${languageInstruction}

Your response must match this exact JSON schema:
{
  "titles": [
    {
      "title": "string — SEO-optimized blog title, compelling and specific",
      "slug": "string — URL-friendly slug derived from title, lowercase, hyphens",
      "excerpt": "string — 2-3 sentence summary of what this post covers",
      "contentType": "string — one of: educational, how-to-guide, industry-trends, case-study, comparison, product-focused, listicle, problem-solution, thought-leadership, news-analysis, interview, tutorial, opinion, roundup, faq-style",
      "style": "string — one of: how-to, listicle, question, controversial, data-driven, story, comparison, definitive-guide, myth-busting, newsjacking",
      "seoScore": "number — estimated SEO effectiveness score 0-100",
      "searchIntent": "string — one of: informational, commercial, transactional, navigational",
      "funnelStage": "string — one of: tofu, mofu, bofu",
      "suggestedKeywords": ["array of 3-7 relevant keywords for this post"],
      "suggestedCTA": "string — recommended call-to-action for this post",
      "primaryKeyword": "string — the single most important keyword for this post",
      "secondaryKeywords": ["array of 2-4 secondary keywords"],
      "metaDescription": "string — SEO meta description, 150-160 characters",
      "trendingKeywords": ["array of 2-3 trending/seasonal keywords related to this topic"]
    }
  ]
}

Generate exactly ${blogCount} titles. Make each one unique and specific to the business context provided.`;

  const userPrompt = `Generate ${blogCount} blog title ideas for this business:${contextStr}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 100000 };
}

// ============================================
// STAGE 3: CONTENT ENHANCEMENT
// ============================================

export function buildBlogContentEnhancementPrompt(inputs: BlogPipelineInputs, partial: PartialBlogAnalysis): PromptResult {
  const languageInstruction = buildLanguageInstruction(inputs.language);

  const titleList = Array.isArray(partial.titles)
    ? partial.titles.map((t: any, i: number) => `${i + 1}. "${t.title}" (${t.contentType}, ${t.funnelStage}, ${t.searchIntent})`).join('\n')
    : '';
  const titleCount = Array.isArray(partial.titles) ? partial.titles.length : 0;

  const strategyContext = [];
  if (partial.blogStrategy?.goals?.length) strategyContext.push(`Goals: ${partial.blogStrategy.goals.join(', ')}`);
  if (partial.seoConfig?.primaryKeywords?.length) strategyContext.push(`Primary Keywords: ${partial.seoConfig.primaryKeywords.join(', ')}`);
  if (partial.blogStrategy?.brandVoice) strategyContext.push(`Brand Voice: ${partial.blogStrategy.brandVoice}`);

  const systemPrompt = `You are a B2B content enhancement specialist. For each of the ${titleCount} blog titles listed, provide detailed content outlines, heading suggestions, internal linking strategies, and SEO refinements.

Each enhancement must be specific to its corresponding title — provide actionable content direction, not generic advice.${JSON_INSTRUCTION}${languageInstruction}

Your response must match this exact JSON schema:
{
  "contentEnhancements": [
    {
      "contentOutline": "string — detailed content outline with H2/H3 section headings, e.g. 'H2: Introduction\\nH2: Key Concepts\\nH3: Sub-topic 1\\nH2: Practical Steps\\nH2: Conclusion'",
      "headingSuggestions": {
        "h1": "string — optimized H1 heading (may differ from title for SEO)",
        "h2s": ["array of 3-5 H2 headings"],
        "h3s": ["array of 2-4 H3 sub-headings"]
      },
      "internalLinkSuggestions": {
        "products": ["array of 1-3 product/service pages this post should link to"],
        "blogs": ["array of 1-3 related blog topics to interlink"],
        "landingPages": ["array of 1-2 relevant landing page topics"],
        "icps": ["array of 1-2 ICP segments this post targets"]
      },
      "contentBrief": "string — writer's brief: angle, key points to cover, data to include, tone guidance",
      "recommendedWordCount": "number — ideal word count for this post, typically 3000-10000",
      "imagePrompt": "string — AI image generation prompt for a featured image",
      "imageAlt": "string — alt text for the featured image",
      "ogImageDescription": "string — Open Graph image description for social sharing"
    }
  ],
  "seoEnhancements": {
    "overallKeywordStrategy": "string — how keywords should be distributed across the blog cluster",
    "internalLinkingStrategy": "string — how these posts should link to each other and to product pages",
    "pillarPageTopics": ["array of 2-3 pillar page topics this cluster could support"]
  },
  "blogClusterTopic": "string — the overarching topic cluster these blogs fall under"
}

The contentEnhancements array MUST have exactly ${titleCount} items, one per title in the same order.`;

  const userPrompt = `Enhance these blog titles with content outlines and SEO strategy:\n\nTitles:\n${titleList}\n${strategyContext.length > 0 ? '\nStrategy Context:\n' + strategyContext.join('\n') : ''}\n\nCompany context:\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 100000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildBlogEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are a B2B blog content 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: 50000 };
}
