/**
 * AI Prompt Library for Email Template Pipeline
 *
 * Generates email templates in 3 stages: template identity,
 * email content & copy, and optimization strategy.
 */

// ============================================
// TYPES
// ============================================

export interface EmailPipelineInputs {
  /**
   * 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;

  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  productNames?: string[];
  productDescriptions?: string[];

  bookTitles?: string[];
  bookDescriptions?: string[];

  courseTitles?: string[];
  courseDescriptions?: string[];

  eventTitles?: string[];
  eventDescriptions?: string[];

  targetCount: number;

  // User-specified generation parameters (from AI Generate modal)
  emailType?: string;
  purpose?: string;
  tone?: string;
  length?: string;
  ctaGoal?: string;
  language?: string;
  additionalContext?: string;
}

export type PartialEmailAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: EmailPipelineInputs): 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.productNames?.length) {
    const productParts: string[] = [];
    inputs.productNames.forEach((name, i) => {
      const desc = inputs.productDescriptions?.[i];
      productParts.push(desc ? `${name}: ${desc}` : name);
    });
    parts.push(`\nProducts:\n${productParts.join('\n')}`);
  }

  if (inputs.bookTitles?.length) {
    const bookParts: string[] = [];
    inputs.bookTitles.forEach((title, i) => {
      const desc = inputs.bookDescriptions?.[i];
      bookParts.push(desc ? `${title}: ${desc}` : title);
    });
    parts.push(`\nBooks:\n${bookParts.join('\n')}`);
  }

  if (inputs.courseTitles?.length) {
    const courseParts: string[] = [];
    inputs.courseTitles.forEach((title, i) => {
      const desc = inputs.courseDescriptions?.[i];
      courseParts.push(desc ? `${title}: ${desc}` : title);
    });
    parts.push(`\nCourses:\n${courseParts.join('\n')}`);
  }

  if (inputs.eventTitles?.length) {
    const eventParts: string[] = [];
    inputs.eventTitles.forEach((title, i) => {
      const desc = inputs.eventDescriptions?.[i];
      eventParts.push(desc ? `${title}: ${desc}` : title);
    });
    parts.push(`\nEvents:\n${eventParts.join('\n')}`);
  }

  return parts.join('\n');
}

const JSON_INSTRUCTION = '\n\nCRITICAL OUTPUT FORMAT RULES:\n1. Respond with ONLY a single valid JSON object.\n2. Do NOT wrap in markdown code fences (no ```json``` or ``` blocks).\n3. Do NOT include any text, explanation, or commentary before or after the JSON.\n4. Ensure all strings are properly escaped. Ensure all arrays and objects are properly closed.\n5. If the response is too long, reduce detail per item rather than producing broken JSON.';

// ============================================
// STAGE 1: EMAIL TEMPLATE IDENTITY
// ============================================

export function buildEmailIdentityPrompt(inputs: EmailPipelineInputs): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B email marketing strategist AI. Generate ${inputs.targetCount} email template concepts for the given company. Each template should target a different email type and purpose, leveraging the company's brand, products, books, courses, and events.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "templates": [
    {
      "name": "string — descriptive template name, e.g. 'Q2 Product Launch Announcement'",
      "type": "string — one of: marketing, newsletter, welcome, promotion, product-launch, event-invitation, announcement, transactional, custom",
      "category": "string — one of: marketing, newsletter, welcome, promotion, product-launch, event, announcement, custom",
      "subjectLine": "string — compelling email subject line, max 200 chars",
      "tone": "string — one of: professional, friendly, casual, formal, persuasive",
      "tags": ["array of 2-4 tags"]
    }
  ]
}

Generate exactly ${inputs.targetCount} templates. Each should cover a different aspect of the business (e.g. product launch, newsletter, event invitation, welcome series, promotion). Choose types and categories that best fit the company's offerings.`;

  const userPrompt = `Generate ${inputs.targetCount} email template concepts for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 40000 };
}

// ============================================
// STAGE 2: EMAIL CONTENT & COPY
// ============================================

export function buildEmailContentPrompt(inputs: EmailPipelineInputs, partial: PartialEmailAnalysis): PromptResult {
  const templatesSummary = (partial.templates || []).map((t: any, i: number) =>
    `Template ${i + 1}: ${t.name || 'N/A'} | Type: ${t.type || 'N/A'} | Category: ${t.category || 'N/A'} | Subject: ${t.subjectLine || 'N/A'} | Tone: ${t.tone || 'N/A'}`
  ).join('\n');

  // Build user-specified parameter instructions when provided via the Generate modal
  const userParams: string[] = [];
  if (inputs.emailType) userParams.push(`- Email Type: ${inputs.emailType}`);
  if (inputs.purpose) userParams.push(`- Purpose: ${inputs.purpose}`);
  if (inputs.tone) userParams.push(`- Tone: ${inputs.tone}`);
  if (inputs.length) userParams.push(`- Length: ${inputs.length}`);
  if (inputs.ctaGoal) userParams.push(`- CTA Goal: ${inputs.ctaGoal}`);
  if (inputs.language && inputs.language !== 'English') userParams.push(`- Language: Generate all text content in ${inputs.language}`);
  if (inputs.additionalContext) userParams.push(`- Additional Context: ${inputs.additionalContext}`);
  const userParamsBlock = userParams.length > 0 ? `\n\nUser-specified requirements (override defaults where applicable):\n${userParams.join('\n')}` : '';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B email copywriter AI. For each template concept, generate the full email content including preview text, body copy, and call-to-action.

Keep each field concise — shorter valid JSON is better than longer broken JSON.${inputs.language && inputs.language !== 'English' ? ` Generate all text content in ${inputs.language}.` : ''}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "templates": [
    {
      "name": "string — same template name from stage 1",
      "subjectLine": "string — refined subject line, max 200 chars",
      "previewText": "string — email preview text shown in inbox, max 200 chars",
      "body": "string — full email body in HTML format. Use <h2>, <p>, <ul>, <li>, <strong>, <a> tags. Keep it professional and on-brand. Include greeting, main content, and sign-off. Max 2000 chars",
      "ctaText": "string — call-to-action button text, max 50 chars, e.g. 'Get Started', 'Register Now', 'Learn More'",
      "ctaUrl": "string — suggested CTA URL path, e.g. '/products', '/events/register', '/courses'",
      "tone": "string — one of: professional, friendly, casual, formal, persuasive",
      "tags": ["array of 2-4 tags"]
    }
  ]
}

Generate content for all ${inputs.targetCount} templates. The body should be rich HTML with proper structure. Each email should feel personalized to the company's brand voice and relevant to its audience.`;

  const userPrompt = `Generate full email content for these templates:\n\n${templatesSummary}\n\nCompany context:\n${buildCompanyContext(inputs)}${userParamsBlock}`;

  return { systemPrompt, userPrompt, maxTokens: 60000 };
}

// ============================================
// STAGE 3: EMAIL STRATEGY & OPTIMIZATION
// ============================================

export function buildEmailStrategyPrompt(inputs: EmailPipelineInputs, partial: PartialEmailAnalysis): PromptResult {
  const templatesSummary = (partial.templates || []).map((t: any, i: number) =>
    `Template ${i + 1}: ${t.name || 'N/A'} | Type: ${t.type || 'N/A'}`
  ).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B email optimization strategist AI. For the given templates, refine status assignments, add optimization notes, and provide email marketing best practices.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "templates": [
    {
      "name": "string — same template name",
      "status": "string — one of: draft, published, archived"
    }
  ],
  "bestPractices": ["array of 3-5 email marketing best practices relevant to these templates"],
  "optimizationTips": ["array of 2-3 tips for maximizing email engagement and conversions"]
}`;

  const userPrompt = `Generate email strategy for:\n\n${templatesSummary}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 30000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildEmailEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B email strategist AI performing a refinement pass. The previous analysis for "${stageName}" had low confidence on certain fields. Provide more specific, detailed content 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.`;

  return { systemPrompt, userPrompt, maxTokens: 20000 };
}