/**
 * AI Prompt Library for Sales Collateral Pipeline
 *
 * Generates sales collateral data in 3 stages using company context, ICP data,
 * product info, and brand strategy as seed input. Follows the multi-item pattern
 * to generate 8 diverse collateral pieces.
 */

// ============================================
// TYPES
// ============================================

export interface SalesCollateralPipelineInputs {
  /**
   * 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
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // Product context
  productNames?: string[];
  productDescriptions?: string[];

  // How many collateral pieces to generate
  targetCount: number;

  // Generation number for variation directives (0-based, increments on each generation)
  generationNumber?: number;
}

export type PartialSalesCollateralAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// VARIATION DIRECTIVES
// ============================================

const SALES_ANGLES = [
  'Problem-Solution — lead with the customer pain point, then position the product as the solution',
  'ROI-Focused — quantify value with metrics, cost savings, time-to-value, or revenue uplift',
  'Benefit-Driven — structure around tangible outcomes and what the customer gains, not features',
  'Customer Success Story — open with a real-world outcome or testimonial-style narrative',
  'Competitive Advantage — directly compare against alternatives, highlighting unique differentiators',
  'Pain Point Focus — deeply explore one critical customer challenge and how you solve it',
  'Industry-Specific Messaging — tailor language, examples, and metrics to the target industry vertical',
  'Strategic Partnership — frame the relationship as a long-term strategic collaboration, not a transaction',
];

const OPENING_STYLES = [
  'Open with a provocative question that challenges the reader\'s status quo',
  'Open with a compelling data point or industry statistic that creates urgency',
  'Open with a brief customer success snapshot — outcome first, then context',
  'Open with a bold value statement that directly addresses the reader\'s biggest concern',
];

const CTA_APPROACHES = [
  'Soft CTA — invite exploration: "See how it works", "Explore the platform"',
  'Value CTA — quantify the next step: "Calculate your savings", "Get your custom quote"',
  'Urgency CTA — limited-time framing: "Book before quarter-end", "Reserve your spot"',
  'Partnership CTA — relationship framing: "Start your journey with us", "Let\'s build together"',
];

const TONE_VARIATIONS = [
  'Authoritative and data-driven — cite numbers, use precise language',
  'Conversational and relatable — write like a trusted advisor, not a vendor',
  'Visionary and aspirational — paint the future state, use forward-looking language',
  'Pragmatic and no-nonsense — focus on facts, skip fluff, get to the point quickly',
];

function pickVariationDirective(generationNumber: number): string {
  const angleIdx = generationNumber % SALES_ANGLES.length;
  const openIdx = generationNumber % OPENING_STYLES.length;
  const ctaIdx = generationNumber % CTA_APPROACHES.length;
  const toneIdx = generationNumber % TONE_VARIATIONS.length;

  return `
GENERATION VARIATION DIRECTIVES (Generation #${generationNumber + 1}):
- Sales Angle: ${SALES_ANGLES[angleIdx]}
- Opening Style: ${OPENING_STYLES[openIdx]}
- CTA Approach: ${CTA_APPROACHES[ctaIdx]}
- Tone: ${TONE_VARIATIONS[toneIdx]}

You MUST follow these directives to produce content distinctly different from previous generations. Each piece should feel like it was written by a different strategist with a different approach.`;
}

// ============================================
// DIVERSITY HINTS
// ============================================

const DIVERSITY_HINTS = [
  'One-pager — concise single-page overview of the company or a specific product, ideal for quick prospect sharing',
  'Brochure — multi-page marketing brochure introducing the company, products, and value proposition',
  'Product deck — presentation-style product overview highlighting features, benefits, and use cases',
  'Case study — success story showcasing a customer challenge, solution, and measurable results',
  'Datasheet — technical specifications and feature comparison sheet for a product or service',
  'Whitepaper — in-depth thought leadership document exploring a industry problem and proposed solution',
  'Pricing sheet — clear pricing breakdown with plans, features, and comparison',
  'Pitch deck — investor or prospect-facing presentation covering vision, market, solution, and ask',
];

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: SalesCollateralPipelineInputs): 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')}`);
  }

  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: COLLATERAL IDENTITY & STRATEGY
// ============================================

export function buildSalesCollateralIdentityPrompt(inputs: SalesCollateralPipelineInputs): PromptResult {
  const count = Math.min(inputs.targetCount, 8);
  const hints = DIVERSITY_HINTS.slice(0, count);
  const diversityLines = hints.map((h, i) => `Piece ${i + 1}: ${h}`).join('\n');
  const genNum = inputs.generationNumber ?? 0;
  const variationDirective = pickVariationDirective(genNum);

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales collateral strategist AI. Generate ${count} diverse sales collateral pieces for the given company. Each piece should target a different collateral type, sales stage, and audience.

${variationDirective}

DIVERSITY GUIDELINES — follow these to ensure variety:
${diversityLines}

Each piece must have a distinct type, funnel stage, audience type, and access level. Cover the full sales journey.

UNIQUENESS REQUIREMENTS:
- Every title must be unique and specific — never use generic titles like "Company Overview" or "Product Sheet"
- Descriptions must differ significantly across pieces — avoid repeating the same phrases
- Each piece should emphasize a different aspect of the company's value (e.g., one focuses on ROI, another on ease-of-use, another on competitive edge)
- Vary the language, vocabulary, and sentence structure across pieces
- Do NOT reuse the same adjectives, buzzwords, or phrasing patterns across multiple pieces${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "collateral": [
    {
      "name": "string — descriptive title, e.g. 'Acme CRM One-Pager for Sales Teams'",
      "description": "string — 1-2 sentence summary of what this collateral contains and when to use it",
      "type": "string — one of: one-pager, brochure, company-profile, media-kit, case-study, whitepaper, datasheet, proposal, product-deck, service-deck, pricing-sheet, pitch-deck, demo-video, product-demo, feature-document, technical-specification, testimonial-asset, roi-document, comparison-sheet, sales-flyer, portfolio, client-presentation, explainer-video",
      "category": "string — one of: sales-presentation, technical-document, marketing-material, client-proposal, pricing, product-education, demo-material",
      "funnelStage": "string — one of: awareness, discovery, qualification, demo, proposal, negotiation, closing, retention",
      "department": "string — department that owns this, e.g. 'Sales', 'Marketing', 'Customer Success'",
      "tags": ["array of 3-5 relevant tags"],
      "industryTags": ["array of 2-3 relevant industry tags"],
      "targetPersona": "string — the persona this collateral targets, e.g. 'VP of Engineering at enterprise SaaS companies'",
      "designBrief": "string — 1-2 sentence brief describing the visual style, format, and key visual elements"
    }
  ]
}

Generate exactly ${count} collateral pieces. The array order must match the diversity guidelines above.`;

  const userPrompt = `Generate ${count} diverse sales collateral pieces for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 4000 };
}

// ============================================
// STAGE 2: COLLATERAL CONTENT & STRUCTURE
// ============================================

export function buildSalesCollateralContentPrompt(inputs: SalesCollateralPipelineInputs, partials: PartialSalesCollateralAnalysis[]): PromptResult {
  const identitySummaries = partials.map((p, i) => {
    const parts = [`Piece ${i + 1}:`];
    if (p.name) parts.push(`  Title: ${p.name}`);
    if (p.type) parts.push(`  Type: ${p.type}`);
    if (p.funnelStage) parts.push(`  Stage: ${p.funnelStage}`);
    if (p.category) parts.push(`  Category: ${p.category}`);
    if (p.targetPersona) parts.push(`  Target: ${p.targetPersona}`);
    return parts.join('\n');
  }).join('\n\n');

  const genNum = inputs.generationNumber ?? 0;
  const variationDirective = pickVariationDirective(genNum);

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales collateral copywriter AI. For each of the ${partials.length} collateral pieces, generate the full content including key messaging, sections, talking points, and call-to-actions.

${variationDirective}

CONTENT VARIATION REQUIREMENTS:
- Each piece's keyMessages must use different wording and framing — avoid repeating the same message patterns
- Value propositions should emphasize different benefits for each piece (e.g., one leads with cost savings, another with time-to-value, another with competitive edge)
- Sections should have unique titles and distinct content angles across pieces
- CallToActions should match the CTA approach specified in the variation directives
- ObjectionResponses should address different objections per piece, not the same generic objections
- Vary vocabulary, sentence structure, and rhetorical devices across pieces

Keep each field concise — 1-3 sentences per field. Be concise — shorter valid JSON is better than longer broken JSON.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "collateral": [
    {
      "name": "string — same title from stage 1",
      "description": "string — expanded description, 2-3 sentences",
      "valueProposition": "string — the core value proposition this collateral communicates, 1-2 sentences",
      "keyMessages": ["array of 3-5 key messages or headlines this collateral should convey"],
      "sections": [
        {
          "title": "string — section title",
          "content": "string — brief content outline or talking points for this section, 1-3 sentences",
          "order": "number — display order starting from 0"
        }
      ],
      "callToAction": "string — primary CTA, e.g. 'Schedule a Demo' or 'Download Full Report'",
      "secondaryCTA": "string — secondary CTA, e.g. 'Learn More' or 'Contact Sales'",
      "talkingPoints": ["array of 3-5 talking points for sales reps using this collateral"],
      "objectionResponses": [
        {
          "objection": "string — common objection this collateral addresses",
          "response": "string — how the collateral addresses it, 1-2 sentences"
        }
      ],
      "suggestedDistributionChannels": ["array of 2-3 channels, e.g. 'email', 'website', 'sales-call'"]
    }
  ]
}

Generate exactly ${partials.length} collateral pieces. Include 3-6 sections per piece and 2-3 objection responses.`;

  const userPrompt = `Generate full content for these sales collateral pieces:\n\n${identitySummaries}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 5000 };
}

// ============================================
// STAGE 3: USAGE GUIDANCE & BEST PRACTICES
// ============================================

export function buildSalesCollateralTrainingPrompt(inputs: SalesCollateralPipelineInputs, partials: PartialSalesCollateralAnalysis[]): PromptResult {
  const identitySummaries = partials.map((p, i) => {
    const parts = [`Piece ${i + 1}:`];
    if (p.name) parts.push(`  ${p.name}`);
    if (p.type) parts.push(`  Type: ${p.type}`);
    return parts.join(' ');
  }).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales enablement AI. For each of the ${partials.length} collateral pieces, generate usage guidance, best practices, and effectiveness tips.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "collateral": [
    {
      "usageNotes": "string — 2-3 sentences about when and how to use this collateral effectively",
      "bestPractices": ["array of 3-5 best practices for distributing and presenting this collateral"],
      "effectivenessTips": ["array of 2-3 tips for maximizing conversion with this collateral"],
      "followUpStrategy": "string — recommended follow-up action after sharing this collateral, 1-2 sentences",
      "idealTiming": "string — when in the sales process this collateral is most effective, e.g. 'After initial discovery call'",
      "successMetrics": ["array of 2-3 metrics to track this collateral's effectiveness"]
    }
  ]
}

Generate exactly ${partials.length} pieces. The array order must match the identity order.`;

  const userPrompt = `Generate usage guidance for these sales collateral pieces:\n\n${identitySummaries}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 3000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildSalesCollateralEnhancementPrompt(
  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 sales collateral strategist AI performing a refinement pass. The previous analysis for "${stageName}" had low confidence on certain fields. Please provide more specific, detailed, and well-reasoned 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, providing more specific and detailed values for the flagged fields.`;

  return { systemPrompt, userPrompt, maxTokens: 2000 };
}