/**
 * AI Prompt Library for Sales Script Pipeline
 *
 * Generates sales script data in 3 stages using company context, ICP data,
 * product info, and brand strategy as seed input. Follows the multi-item
 * pattern (like Testimonial pipeline) to generate 10 diverse scripts.
 */

// ============================================
// TYPES
// ============================================

export interface SalesScriptPipelineInputs {
  // "Our" company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];
  companyTargetGeography?: string;
  companyCountry?: string;

  // ICP context
  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];
  icpChallenges?: string[];

  // Brand strategy context
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // Product context
  productNames?: string[];
  productDescriptions?: string[];

  // How many scripts to generate
  targetCount: number;

  // Language for script generation
  language?: string; // 'English' or 'Hindi' - default is 'English'

  // Custom instructions from user
  customInstructions?: string;
}

export type PartialSalesScriptAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// DIVERSITY HINTS (ensures scripts cover different angles)
// ============================================

const DIVERSITY_HINTS = [
  'Cold outreach to a new prospect — break the ice, establish credibility, and book a discovery call',
  'Warm follow-up after a prospect downloaded a resource or attended a webinar — nurture the lead toward a meeting',
  'Discovery/qualification call — uncover pain points, budget, and decision-making process',
  'Product demo pitch — showcase features, map to the prospect\'s pain points, and handle live questions',
  'Objection handling — address common concerns like pricing, timing, competitors, and "not a priority"',
  'Closing conversation — create urgency, summarize value, and ask for the commitment',
  'Upsell/cross-sell to an existing customer — expand the account with relevant add-ons',
  'Reactivation of a lost or churned customer — re-engage with new value and win them back',
  'Referral request from a happy customer — ask for introductions to their network',
  'Retention/renewal conversation — reinforce ROI, address concerns, and lock in the renewal',
];

// ============================================
// FUNNEL-STAGE COPY STRATEGY
// ============================================

const FUNNEL_STAGE_COPY_STRATEGY: Record<string, string> = {
  awareness: 'Educational, curiosity-driven, low-commitment. Focus on creating interest and opening minds. Avoid hard sells. Use thought-provoking questions, industry statistics, and "did you know" style hooks. The prospect does not yet know they have a problem.',
  interest: 'Value-focused, social-proof, medium-commitment. Focus on demonstrating relevance and building credibility. Use case studies, testimonials, and specific outcomes. The prospect knows they have a problem but is evaluating options.',
  consideration: 'Comparison-oriented, ROI-focused, demo-oriented. Focus on differentiating from competitors and showing measurable value. Use specific metrics, competitive comparisons, and personalized demos. The prospect is actively evaluating solutions.',
  decision: 'Urgency, risk-reversal, guarantee, strong CTA. Focus on removing objections and creating momentum. Use time-limited offers, guarantees, and social proof from similar customers. The prospect is ready to commit but needs a final push.',
  purchase: 'Transaction-focused, onboarding, immediate action. Focus on making the process smooth and immediate. Use clear next steps, onboarding previews, and instant-access messaging. The prospect has decided and needs to act.',
  retention: 'Value-reinforcement, ROI-reminder, loyalty-building. Focus on reminding customers of ongoing value. Use success metrics, milestone celebrations, and expansion opportunities. The customer is already on board.',
  advocacy: 'Referral-request, testimonial-ask, community-building. Focus on empowering happy customers to spread the word. Use specific ask language, make it easy, and offer incentives. The customer is a promoter.',
};

// ============================================
// CHANNEL COPY STRATEGY
// ============================================

const CHANNEL_COPY_STRATEGY: Record<string, string> = {
  phone: 'Conversational tone, allow pauses for prospect response, professional but warm. Use short sentences. Ask permission before pitching. Always confirm the prospect has time to talk.',
  email: 'Subject line is critical — must create curiosity without being clickbait. Body should be scannable: short paragraphs, bullet points, one clear CTA. Personalize the first line. Keep under 200 words for cold outreach.',
  linkedin: 'Professional networking tone, connection-first approach. Reference shared connections or groups. Lead with value or insight, not a pitch. Use social proof. Keep messages concise and conversational.',
  whatsapp: 'Casual, brief, emoji-friendly. Keep messages short (under 100 words). Use a warm, personal tone. Avoid corporate jargon. Lead with the value prop in the first 2 sentences.',
  zoom: 'Demo-oriented, visual, interactive. Prepare screen-share moments. Ask discovery questions early. Use the prospect\'s name frequently. Build in interaction points to maintain engagement.',
  'google-meet': 'Same as zoom — demo-oriented, visual, interactive. Prepare screen-share moments. Ask discovery questions early. Use the prospect\'s name frequently.',
  'in-person': 'Relationship-building, handshake moments, read the room. Mirror the prospect\'s energy. Use storytelling. Bring physical collateral if appropriate. Focus on connection before content.',
  sms: 'Ultra-concise, action-oriented. Maximum 160 characters. One CTA per message. Use personalization (first name). No jargon. Direct and time-sensitive.',
  'voice-note': 'Warm, personal, 60-second format. Start with context for why you are reaching out. Speak naturally — not reading a script. End with a clear, low-pressure question that invites response.',
};

// ============================================
// BANNED PHRASES & ANTI-GENERIC INSTRUCTION
// ============================================

const BANNED_PHRASES = [
  "I'd love to",
  "We help businesses",
  "Let me show you",
  "In today's competitive landscape",
  "Streamline your operations",
  "Take your business to the next level",
  "Transform your business",
  "Unlock your potential",
  "Cutting-edge solution",
  "Revolutionize the way you work",
  "Game-changer",
  "One-stop shop",
  "Synergy",
  "Best-in-class",
  "World-class",
  "Seamless integration",
  "End-to-end solution",
  "Robust platform",
  "Leverage our",
  "Empower your team",
  "Drive results",
  "At the end of the day",
  "Move the needle",
  "Low-hanging fruit",
  "Think outside the box",
  "Value-added",
];

const ANTI_GENERIC_INSTRUCTION = `

CRITICAL QUALITY RULES:
- Do NOT use generic placeholder text. Every opening line, hook, value proposition, and CTA must be specific to THIS company, industry, product, and ICP.
- The following phrases are BANNED — do NOT use them anywhere in your output: ${BANNED_PHRASES.map(p => `"${p}"`).join(', ')}.
- Opening lines MUST reference the prospect's specific industry, role, pain point, or a relevant statistic. NOT "Hi, I'm reaching out because..."
- Hooks MUST create genuine curiosity with a specific claim, statistic, or insight tied to the ICP's stated challenges. NOT generic curiosity bait.
- Value propositions MUST tie value directly to the ICP's stated pain points with measurable outcomes. NOT "We help businesses grow."
- CTAs MUST use specific action verbs and indicate what happens next. NOT "Let's connect" or "Reach out."
- Objection responses MUST address the specific objection with a relevant example, statistic, or reframing. NOT "I understand your concern."
- Each script's content MUST be completely distinct from every other script. Do NOT reuse opening lines, hooks, value propositions, CTAs, or objection responses across scripts.`;

// ============================================
// SALES ANGLES (ensures each script uses a different persuasive approach)
// ============================================

export interface SalesAngle {
  name: string;
  description: string;
  openingGuidance: string;
  hookGuidance: string;
  valuePropGuidance: string;
}

export const SALES_ANGLES: SalesAngle[] = [
  {
    name: 'Problem-Solution',
    description: 'Lead with the prospect\'s specific pain point, then present the product as the direct remedy.',
    openingGuidance: 'Open with a specific, verifiable pain point the ICP faces. Name the problem directly.',
    hookGuidance: 'Hook by quantifying the cost of inaction — lost revenue, wasted hours, missed targets.',
    valuePropGuidance: 'Position value as the elimination of the named problem, with measurable relief.',
  },
  {
    name: 'Storytelling',
    description: 'Use a narrative arc — a customer in a similar situation who succeeded — to build emotional connection.',
    openingGuidance: 'Open with a brief, relatable micro-story about someone like the prospect.',
    hookGuidance: 'Hook by revealing a surprising twist or outcome in the story that creates curiosity.',
    valuePropGuidance: 'Frame value through the story\'s outcome — show what changed for the customer.',
  },
  {
    name: 'Consultative',
    description: 'Position the seller as a trusted advisor asking thoughtful questions before offering solutions.',
    openingGuidance: 'Open with a genuine question about the prospect\'s current situation or challenges.',
    hookGuidance: 'Hook by sharing a diagnostic insight or benchmark that reframes how they see their problem.',
    valuePropGuidance: 'Present value as a collaborative roadmap — what the journey looks like together.',
  },
  {
    name: 'Value-Based',
    description: 'Lead with concrete, quantifiable value — ROI numbers, time saved, cost reduced — before explaining features.',
    openingGuidance: 'Open with a specific, credible number or metric relevant to the prospect\'s industry.',
    hookGuidance: 'Hook by contrasting the prospect\'s current state with a quantified better state.',
    valuePropGuidance: 'State value in hard numbers — dollars saved, hours recovered, percentage improvement.',
  },
  {
    name: 'Urgency-Based',
    description: 'Create time-sensitive relevance by tying the outreach to a market shift, deadline, or compelling event.',
    openingGuidance: 'Open by referencing a specific timely event, trend, or deadline that makes this conversation urgent.',
    hookGuidance: 'Hook by showing what changes if they wait — the cost of delay or the advantage of acting now.',
    valuePropGuidance: 'Position value as an immediate opportunity with a window that is closing.',
  },
  {
    name: 'ROI-Focused',
    description: 'Build the case on financial return — investment vs. payoff, payback period, total cost of ownership.',
    openingGuidance: 'Open by asking about their current investment in the problem area or citing an industry ROI benchmark.',
    hookGuidance: 'Hook by presenting a realistic ROI scenario with a short payback period.',
    valuePropGuidance: 'Deliver value as a clear investment thesis — cost, payback timeline, and projected return.',
  },
  {
    name: 'Relationship Building',
    description: 'Prioritize trust and rapport — reference shared connections, mutual interests, or community before any pitch.',
    openingGuidance: 'Open with a genuine personal connection — a shared contact, event, or interest that establishes warmth.',
    hookGuidance: 'Hook by offering something genuinely useful with no strings attached — a resource, insight, or introduction.',
    valuePropGuidance: 'Present value as a long-term partnership benefit, not a one-time transaction.',
  },
  {
    name: 'Challenger',
    description: 'Challenge the prospect\'s assumptions with a bold, data-backed insight that reframes their thinking.',
    openingGuidance: 'Open by stating a counterintuitive or provocative insight about their industry or approach.',
    hookGuidance: 'Hook by revealing a hidden cost or missed opportunity they have not considered.',
    valuePropGuidance: 'Present value by contrasting their current approach with a fundamentally better way, backed by evidence.',
  },
];

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: SalesScriptPipelineInputs): 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.
  //
  // `customInstructions` was only read by `buildSingleSalesScriptPrompt` (the
  // one-by-one streaming path), so the /auto-fill pipeline — identity, content
  // and training prompts — never saw the brief at all.
  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.companyTargetGeography) parts.push(`Target Geography: ${inputs.companyTargetGeography}`);
  if (inputs.companyCountry) parts.push(`Country: ${inputs.companyCountry}`);

  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(', ')}`);
    if (inputs.icpChallenges?.length) icpParts.push(`Key Challenges: ${inputs.icpChallenges.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. Do NOT include a "thinking" section or notes — only the JSON object.\n5. Ensure all strings are properly escaped. Ensure all arrays and objects are properly closed.\n6. If the response is too long, reduce detail per item rather than producing broken JSON.';

// ============================================
// STAGE 1: SCRIPT IDENTITY & STRATEGY
// ============================================

export function buildSalesScriptIdentityPrompt(inputs: SalesScriptPipelineInputs): PromptResult {
  const count = Math.min(inputs.targetCount, 10);
  const hints = DIVERSITY_HINTS.slice(0, count);
  const diversityLines = hints.map((h, i) => `Script ${i + 1}: ${h}`).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales strategy AI. Generate ${count} diverse sales scripts for the given company. Each script should target a different scenario, funnel stage, and audience.

DIVERSITY GUIDELINES — follow these to ensure variety:
${diversityLines}

UNIQUENESS CONSTRAINT: No two scripts may share the same combination of scriptType + funnelStage + channels. Each script must cover a genuinely distinct sales scenario — do NOT generate multiple scripts that could serve the same conversation.

Cover the full sales journey from cold outreach to closing and retention.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "scripts": [
    {
      "title": "string — descriptive script name, e.g. 'Cold Outreach — Book Discovery Call with SaaS VPs'",
      "description": "string — 1-2 sentence summary of when and how to use this script",
      "scriptType": "string — one of: cold-call, warm-call, qualification, discovery, demo, sales-pitch, follow-up, negotiation, closing, whatsapp, email, linkedin, voice-note, appointment, reactivation, referral, upselling, cross-selling, retention, renewal, customer-success, objection-handling",
      "funnelStage": "string — one of: awareness, interest, consideration, decision, purchase, retention, advocacy",
      "audienceType": "string — one of: prospect, lead, opportunity, customer, partner, investor",
      "priority": "string — one of: low, medium, high, critical",
      "status": "string — one of: draft, review. Assign 'review' if the script is complete and ready for human review. Assign 'draft' if it needs editing or refinement. Do NOT use 'approved', 'published', or 'archived' for new scripts.",
      "channels": ["array of 1-2 channels from: phone, whatsapp, linkedin, email, zoom, google-meet, in-person, sms, voice-note"],
      "targetIndustry": "string — the target industry for this script",
      "targetPersona": "string — the specific persona/job title this script targets, e.g. 'VP of Sales at mid-market SaaS companies'",
      "brandTone": "string — brand tone for this script, e.g. 'Consultative and empathetic'",
      "communicationStyle": "string — communication style, e.g. 'Question-led, value-first approach'",
      "category": "string — script category, e.g. 'outbound', 'inbound', 'expansion', 'retention'",
      "tags": ["array of 3-5 relevant tags, e.g. 'cold-outreach', 'saas', 'vp-sales'"]
    }
  ]
}

Generate exactly ${count} scripts. The array order must match the diversity guidelines above.`;

  const userPrompt = `Generate ${count} diverse sales scripts for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 5000 };
}

// ============================================
// STAGE 2: SCRIPT CONTENT & STRUCTURE
// ============================================

export function buildSalesScriptContentPrompt(inputs: SalesScriptPipelineInputs, partials: PartialSalesScriptAnalysis[]): PromptResult {
  // Build enriched per-script context with diversity hints, funnel strategy, and channel strategy
  const enrichedSummaries = partials.map((p, i) => {
    const parts = [`SCRIPT ${i + 1}:`];
    if (p.title) parts.push(`  Title: ${p.title}`);
    if (p.scriptType) parts.push(`  Type: ${p.scriptType}`);
    if (p.funnelStage) parts.push(`  Funnel Stage: ${p.funnelStage}`);
    if (p.audienceType) parts.push(`  Audience: ${p.audienceType}`);
    if (p.channels) parts.push(`  Channels: ${Array.isArray(p.channels) ? p.channels.join(', ') : p.channels}`);
    if (p.targetPersona) parts.push(`  Target Persona: ${p.targetPersona}`);
    if (p.brandTone) parts.push(`  Brand Tone: ${p.brandTone}`);

    // Add diversity hint for this script
    const hint = DIVERSITY_HINTS[i % DIVERSITY_HINTS.length];
    parts.push(`  Diversity Angle: ${hint}`);

    // Add funnel-stage copy strategy
    const funnelStage = p.funnelStage as string | undefined;
    if (funnelStage && FUNNEL_STAGE_COPY_STRATEGY[funnelStage]) {
      parts.push(`  Funnel Copy Strategy: ${FUNNEL_STAGE_COPY_STRATEGY[funnelStage]}`);
    }

    // Add channel-specific copy guidance
    const channels = Array.isArray(p.channels) ? p.channels : (p.channels ? [p.channels] : []);
    const channelStrategies = channels
      .filter((c: string) => CHANNEL_COPY_STRATEGY[c])
      .map((c: string) => `${c}: ${CHANNEL_COPY_STRATEGY[c]}`);
    if (channelStrategies.length > 0) {
      parts.push(`  Channel Guidance:\n  ${channelStrategies.join('\n  ')}`);
    }

    // Add sales angle assignment for this script
    const angle = SALES_ANGLES[i % SALES_ANGLES.length];
    parts.push(`  Sales Angle: ${angle.name} — ${angle.description}`);
    parts.push(`  Opening Guidance: ${angle.openingGuidance}`);
    parts.push(`  Hook Guidance: ${angle.hookGuidance}`);
    parts.push(`  Value Prop Guidance: ${angle.valuePropGuidance}`);

    return parts.join('\n');
  }).join('\n\n');

  const sectionTypes = 'opening, hook, qualification, pain-discovery, value-position, offer, objection, trust, social-proof, closing, follow-up, exit';

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales script copywriter AI. For each of the ${partials.length} scripts, generate the full conversational content including opening lines, hooks, value propositions, structured sections, qualification questions, and objection responses.

Each script should be a complete, ready-to-use conversation guide that a sales rep can follow. Keep each section content to 1-3 sentences. Keep tips to 1 short sentence each. Be concise — shorter valid JSON is better than longer broken JSON.

Section types available: ${sectionTypes}. Include 3-5 sections per script that are relevant to the script type and funnel stage.

CRITICAL UNIQUENESS REQUIREMENT:
- Every script is assigned a DIFFERENT Sales Angle. The opening line, hook, and value proposition MUST follow the angle-specific guidance provided for that script. A Problem-Solution script opens differently from a Storytelling script. Do NOT fall back to generic phrasing.
- Every script MUST have DISTINCT opening lines, hooks, value propositions, and CTAs. Do NOT reuse or paraphrase the same content across scripts.
- Each script's content MUST reflect its SPECIFIC funnel stage strategy and channel guidance — an awareness-stage script reads completely differently from a decision-stage script.
- Each script's content MUST reflect its SPECIFIC channel — a phone script sounds conversational with pauses, an email script is scannable with a strong subject line, a LinkedIn script leads with connection and value.${ANTI_GENERIC_INSTRUCTION}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "scripts": [
    {
      "openingLine": "string — the first thing to say, MUST reference the prospect's specific industry, role, or pain point. e.g. 'Hi [Name], I noticed your team is scaling fast — are you still using [manual process]?'",
      "hook": "string — attention-grabbing statement that creates curiosity, 1-2 sentences. MUST include a specific claim, statistic, or insight tied to the ICP's stated challenges.",
      "valueProposition": "string — clear value prop tailored to this audience, 2-3 sentences. MUST tie value directly to the ICP's stated pain points with measurable outcomes.",
      "offerPresentation": "string — how to present the offer, 1-2 sentences",
      "closingCTA": "string — the closing call-to-action. MUST use a specific action verb and indicate what happens next. e.g. 'Would Tuesday at 2pm work for a 15-minute demo?'",
      "followUpCTA": "string — follow-up CTA if they say maybe/later",
      "exitResponse": "string — graceful exit if they say no, keeping the door open",
      "messagingGuidelines": "string — key messaging guidelines for this script, 1-2 sentences",
      "sections": [
        {
          "type": "string — one of: ${sectionTypes}",
          "title": "string — section title",
          "content": "string — the actual script content/conversation for this section, 2-5 sentences of natural dialogue",
          "order": "number — display order starting from 0",
          "isRequired": "boolean — whether this section is essential",
          "tips": ["array of 1-3 practical tips for delivering this section well"]
        }
      ],
      "qualificationQuestions": [
        {
          "question": "string — the qualification question to ask",
          "purpose": "string — why you're asking this, e.g. 'Understand budget availability'",
          "followUpIfYes": "string — what to say if they answer positively",
          "followUpIfNo": "string — what to say if they answer negatively",
          "order": "number — question order starting from 0"
        }
      ],
      "objectionResponses": [
        {
          "objection": "string — the common objection, e.g. 'We don't have budget right now'",
          "response": "string — how to respond to this objection, 2-3 sentences",
          "trustBuildingLine": "string — a trust-building line to follow up",
          "ctaSuggestion": "string — suggested CTA after handling the objection",
          "order": "number — objection order starting from 0"
        }
      ]
    }
  ]
}

Generate exactly ${partials.length} scripts. The array order must match the identity order. Include 3-5 qualification questions and 2-4 objection responses per script.`;

  const userPrompt = `Generate full content for these sales scripts:\n\n${enrichedSummaries}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 6000 };
}

// ============================================
// STAGE 3: TRAINING & BEST PRACTICES
// ============================================

export function buildSalesScriptTrainingPrompt(inputs: SalesScriptPipelineInputs, partials: PartialSalesScriptAnalysis[]): PromptResult {
  // Enrich identity summaries with diversity hints and funnel stage info
  const identitySummaries = partials.map((p, i) => {
    const parts = [`Script ${i + 1}:`];
    if (p.title) parts.push(`  Title: ${p.title}`);
    if (p.scriptType) parts.push(`  Type: ${p.scriptType}`);
    if (p.funnelStage) parts.push(`  Funnel Stage: ${p.funnelStage}`);
    if (p.audienceType) parts.push(`  Audience: ${p.audienceType}`);
    if (p.channels) parts.push(`  Channels: ${Array.isArray(p.channels) ? p.channels.join(', ') : p.channels}`);

    // Add diversity hint
    const hint = DIVERSITY_HINTS[i % DIVERSITY_HINTS.length];
    parts.push(`  Diversity Angle: ${hint}`);

    // Add funnel-stage strategy
    const funnelStage = p.funnelStage as string | undefined;
    if (funnelStage && FUNNEL_STAGE_COPY_STRATEGY[funnelStage]) {
      parts.push(`  Funnel Strategy: ${FUNNEL_STAGE_COPY_STRATEGY[funnelStage]}`);
    }

    return parts.join('\n');
  }).join('\n\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales training AI. For each of the ${partials.length} scripts, generate training notes, best practices, coaching notes, and conversation branches.

Each script's training content MUST be specific to its funnel stage and script type. A cold-call script's training notes are fundamentally different from a retention script's training notes. Do NOT produce generic training advice that could apply to any script.

Conversation branches define what to do when the prospect responds in different ways (positive, negative, neutral, asks question).${ANTI_GENERIC_INSTRUCTION}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "scripts": [
    {
      "trainingNotes": "string — 2-4 sentences of training guidance SPECIFIC to this script type and funnel stage",
      "bestPractices": ["array of 3-5 practical best practices tailored to this script type and channel"],
      "callExamples": ["array of 2-3 example phrases or transitions reps can use — specific to the script context"],
      "coachingNotes": "string — 1-2 sentences of coaching advice for experienced reps, tied to this script's scenario",
      "conversationBranches": [
        {
          "trigger": "string — the prospect's likely response, specific to this script's context",
          "response": "string — how to respond, 1-2 sentences, specific to this scenario",
          "nextSection": "string — which section to go to next, e.g. 'value-position'",
          "order": "number — branch order starting from 0"
        }
      ]
    }
  ]
}

Generate exactly ${partials.length} scripts. The array order must match the identity order. Include 3-5 conversation branches per script.`;

  const userPrompt = `Generate training content for these sales scripts:\n\n${identitySummaries}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 5000 };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence retry)
// ============================================

export function buildSalesScriptEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  // Build per-field improvement criteria
  const fieldCriteria: Record<string, string> = {
    openingLine: 'Must reference the prospect\'s specific industry, role, or pain point. No generic greetings.',
    hook: 'Must include a specific claim, statistic, or insight tied to the ICP\'s challenges. No generic curiosity bait.',
    valueProposition: 'Must tie value directly to the ICP\'s stated pain points with measurable outcomes. No "We help businesses grow."',
    offerPresentation: 'Must describe a specific offer mechanism tied to the company\'s product/service.',
    closingCTA: 'Must use a specific action verb and indicate what happens next. No "Let\'s connect" or "Reach out."',
    followUpCTA: 'Must propose a concrete next step with a timeframe or specific action.',
    exitResponse: 'Must leave the door open with a specific reason to reconnect later.',
    messagingGuidelines: 'Must provide script-specific messaging direction, not generic advice.',
    sections: 'Each section\'s content must be specific to the script\'s funnel stage and channel — no generic filler.',
    trainingNotes: 'Must be specific to the script type and funnel stage — not generic advice.',
    bestPractices: 'Must be actionable practices specific to this script\'s channel and scenario.',
    callExamples: 'Must include realistic phrases a rep could actually say in this specific script context.',
    coachingNotes: 'Must address a specific challenge reps face with this type of script.',
    conversationBranches: 'Each branch must be specific to the script\'s funnel stage and scenario.',
    qualificationQuestions: 'Questions must be tailored to the ICP\'s specific pain points and buying process.',
    objectionResponses: 'Responses must address specific objections with concrete examples or reframings.',
  };

  const criteriaLines = lowConfidenceFields
    .map(f => `- ${f}: ${fieldCriteria[f] || 'Must be specific, detailed, and business-relevant. No generic text.'}`)
    .join('\n');

  const bannedPhrasesList = BANNED_PHRASES.slice(0, 10).map(p => `"${p}"`).join(', ');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B sales strategy AI performing a refinement pass on sales scripts. The previous analysis for "${stageName}" had low confidence on certain fields. Provide more specific, detailed, and well-reasoned content for the indicated fields.

PER-FIELD IMPROVEMENT CRITERIA:
${criteriaLines}

Do NOT use these banned phrases: ${bannedPhrasesList}, etc. All content must be specific to the company, industry, ICP, and product — no generic filler.${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. Each improved field must meet the per-field improvement criteria listed above.`;

  return { systemPrompt, userPrompt, maxTokens: 6000 };
}

// ============================================
// REGENERATION PROMPT (for duplicate content)
// ============================================

export function buildSalesScriptRegenerationPrompt(
  inputs: SalesScriptPipelineInputs,
  existingScript: Record<string, any>,
  angle: SalesAngle,
  avoidContent: Record<string, string[]>,
  scriptIndex: number
): PromptResult {
  const avoidLines = Object.entries(avoidContent)
    .filter(([, values]) => values.length > 0)
    .map(([field, values]) => {
      const fieldLabel = field === 'openingLine' ? 'Opening Line' :
                         field === 'hook' ? 'Hook' :
                         field === 'valueProposition' ? 'Value Proposition' : field;
      return `${fieldLabel} — do NOT produce content similar to:\n${values.map(v => `  "${v}"`).join('\n')}`;
    })
    .join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are regenerating the content for a sales script that had duplicate content. You MUST produce completely original content that is distinct from the content listed under "DO NOT DUPLICATE".

SALES ANGLE: ${angle.name} — ${angle.description}
- Opening Line MUST follow: ${angle.openingGuidance}
- Hook MUST follow: ${angle.hookGuidance}
- Value Proposition MUST follow: ${angle.valuePropGuidance}

DO NOT DUPLICATE the following content (it was already used by another script in the same batch):
${avoidLines}

${ANTI_GENERIC_INSTRUCTION}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "scripts": [
    {
      "openingLine": "string — a completely new opening line following the ${angle.name} angle",
      "hook": "string — a completely new hook following the ${angle.name} angle",
      "valueProposition": "string — a completely new value proposition following the ${angle.name} angle",
      "offerPresentation": "string — how to present the offer",
      "closingCTA": "string — the closing call-to-action",
      "followUpCTA": "string — follow-up CTA",
      "exitResponse": "string — graceful exit",
      "messagingGuidelines": "string — key messaging guidelines"
    }
  ]
}

Generate exactly 1 script.`;

  const userPrompt = `Regenerate content for Script ${scriptIndex + 1} using the "${angle.name}" sales angle for:\n\n${buildCompanyContext(inputs)}\n\nExisting script identity:\nTitle: ${existingScript.title || 'N/A'}\nType: ${existingScript.scriptType || 'N/A'}\nFunnel Stage: ${existingScript.funnelStage || 'N/A'}\nTarget Persona: ${existingScript.targetPersona || 'N/A'}\nChannels: ${Array.isArray(existingScript.channels) ? existingScript.channels.join(', ') : 'N/A'}`;

  return { systemPrompt, userPrompt, maxTokens: 2000 };
}

// ============================================
// BATCH REGENERATION PROMPT (all duplicates in one call)
// ============================================

export interface DuplicateScriptInfo {
  scriptIndex: number;
  existingScript: Record<string, any>;
  angle: SalesAngle;
  avoidContent: Record<string, string[]>;
}

export function buildSalesScriptBatchRegenerationPrompt(
  inputs: SalesScriptPipelineInputs,
  duplicates: DuplicateScriptInfo[]
): PromptResult {
  const scriptSpecs = duplicates.map((d) => {
    const angle = d.angle;
    const avoidLines = Object.entries(d.avoidContent)
      .filter(([, values]) => values.length > 0)
      .map(([field, values]) => {
        const fieldLabel = field === 'openingLine' ? 'Opening Line' :
                           field === 'hook' ? 'Hook' :
                           field === 'valueProposition' ? 'Value Proposition' : field;
        return `${fieldLabel}: Do NOT produce content similar to "${values[0].substring(0, 80)}..."`;
      }).join('; ');

    return `Script ${d.scriptIndex + 1}: Angle=${angle.name} | Title=${d.existingScript.title || 'N/A'} | Type=${d.existingScript.scriptType || 'N/A'} | Funnel=${d.existingScript.funnelStage || 'N/A'} | Persona=${d.existingScript.targetPersona || 'N/A'} | Channels=${Array.isArray(d.existingScript.channels) ? d.existingScript.channels.join(', ') : 'N/A'} | Avoid: ${avoidLines || 'None'}`;
  }).join('\n');

  const angleGuides = duplicates.map((d) =>
    `Script ${d.scriptIndex + 1} (${d.angle.name}): Opening="${d.angle.openingGuidance}" Hook="${d.angle.hookGuidance}" ValueProp="${d.angle.valuePropGuidance}"`
  ).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are regenerating content for ${duplicates.length} sales scripts that had duplicate content. You MUST produce completely original content for each script, distinct from the "Avoid" content listed for each.

ANGLE-SPECIFIC GUIDANCE (each script MUST follow its assigned angle):
${angleGuides}

${ANTI_GENERIC_INSTRUCTION}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "scripts": [
    {
      "openingLine": "string",
      "hook": "string",
      "valueProposition": "string",
      "offerPresentation": "string",
      "closingCTA": "string",
      "followUpCTA": "string",
      "exitResponse": "string",
      "messagingGuidelines": "string"
    }
  ]
}

Generate exactly ${duplicates.length} scripts. The array order must match the script specs below.`;

  const userPrompt = `Regenerate content for these ${duplicates.length} scripts for:\n\n${buildCompanyContext(inputs)}\n\n${scriptSpecs}`;

  return { systemPrompt, userPrompt, maxTokens: 4000 };
}

// ============================================
// SINGLE-CALL PROMPT (one complete script in one AI call)
// Used by the streaming endpoint for fast one-by-one generation.
// ============================================

export function buildSingleSalesScriptPrompt(
  inputs: SalesScriptPipelineInputs,
  scriptIndex: number,
  existingScripts: { openingLine?: string; hook?: string; valueProposition?: string }[] = [],
): PromptResult {
  const angle = SALES_ANGLES[scriptIndex % SALES_ANGLES.length];
  const hint = DIVERSITY_HINTS[scriptIndex % DIVERSITY_HINTS.length];

  // Build avoid-content list from already-generated scripts
  const avoidLines: string[] = [];
  if (existingScripts.length > 0) {
    avoidLines.push('CRITICAL: Do NOT produce content similar to any of these already-used lines:');
    for (let i = 0; i < existingScripts.length; i++) {
      const s = existingScripts[i];
      if (s.openingLine) avoidLines.push(`  Existing Opening ${i + 1}: "${s.openingLine.substring(0, 100)}"`);
      if (s.hook) avoidLines.push(`  Existing Hook ${i + 1}: "${s.hook.substring(0, 100)}"`);
      if (s.valueProposition) avoidLines.push(`  Existing ValueProp ${i + 1}: "${s.valueProposition.substring(0, 100)}"`);
    }
  }

  const sectionTypes = 'opening, hook, qualification, pain-discovery, value-position, offer, objection, trust, social-proof, closing, follow-up, exit';

  // Language instruction
  const languageInstruction = inputs.language && inputs.language.toLowerCase() === 'hindi'
    ? `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (title, description, opening lines, hooks, value propositions, sections, qualification questions, objection responses, CTAs, training notes, and best practices) entirely in Hindi using Devanagari script (हिंदी देवनागरी लिपि). Do NOT use English anywhere. All text must be natural, fluent Hindi appropriate for B2B sales contexts in India.`
    : inputs.language && inputs.language.toLowerCase() === 'marathi'
    ? `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content (title, description, opening lines, hooks, value propositions, sections, qualification questions, objection responses, CTAs, training notes, and best practices) entirely in Marathi using Devanagari script (मराठी देवनागरी लिपि). Do NOT use English anywhere. All text must be natural, fluent Marathi appropriate for B2B sales contexts in Maharashtra, India.`
    : inputs.language && inputs.language.toLowerCase() !== 'english'
    ? `\n\nIMPORTANT LANGUAGE REQUIREMENT: Generate ALL content in ${inputs.language}. All text (title, description, opening lines, hooks, value propositions, sections, qualification questions, objection responses, CTAs, training notes, and best practices) must be in the specified language.`
    : ''; // Default to English - no additional instruction needed

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert B2B sales strategist and copywriter. Generate ONE complete, production-ready sales script in a single response. This script must be entirely original, specific to the given company and ICP, and ready for a sales rep to use immediately.${languageInstruction}

SALES ANGLE: ${angle.name} — ${angle.description}
- Opening MUST follow: ${angle.openingGuidance}
- Hook MUST follow: ${angle.hookGuidance}
- Value Prop MUST follow: ${angle.valuePropGuidance}

SCENARIO: ${hint}

${avoidLines.length > 1 ? avoidLines.join('\n') : ''}

${ANTI_GENERIC_INSTRUCTION}

${JSON_INSTRUCTION}

Your response must match this EXACT JSON schema:
{
  "title": "string — descriptive script name, e.g. 'Cold Outreach — Book Discovery Call with SaaS VPs'",
  "description": "string — 1-2 sentence summary of when and how to use this script",
  "scriptType": "string — one of: cold-call, warm-call, qualification, discovery, demo, sales-pitch, follow-up, negotiation, closing, whatsapp, email, linkedin, voice-note, appointment, reactivation, referral, upselling, cross-selling, retention, renewal, customer-success, objection-handling",
  "funnelStage": "string — one of: awareness, interest, consideration, decision, purchase, retention, advocacy",
  "audienceType": "string — one of: prospect, lead, opportunity, customer, partner, investor",
  "priority": "string — one of: low, medium, high, critical",
  "status": "string — one of: draft, review. Assign 'review' if the script is complete with all sections fully fleshed out and ready for human review. Assign 'draft' if the script needs significant editing or refinement before review.",
  "channels": ["1-2 channels from: phone, whatsapp, linkedin, email, zoom, google-meet, in-person, sms, voice-note"],
  "targetIndustry": "string",
  "targetPersona": "string",
  "brandTone": "string",
  "communicationStyle": "string",
  "category": "string — one of: outbound, inbound, expansion, retention",
  "tags": ["3-5 relevant tags"],
  "openingLine": "string — the first thing to say. MUST reference the prospect's specific industry, role, or pain point.",
  "hook": "string — attention-grabbing statement, 1-2 sentences. MUST include a specific claim, statistic, or insight.",
  "valueProposition": "string — clear value prop, 2-3 sentences. MUST tie to ICP's pain points with measurable outcomes.",
  "offerPresentation": "string — how to present the offer, 1-2 sentences",
  "closingCTA": "string — the closing CTA. MUST use a specific action verb.",
  "followUpCTA": "string — follow-up CTA if they say maybe/later",
  "exitResponse": "string — graceful exit if they say no",
  "messagingGuidelines": "string — key messaging guidelines, 1-2 sentences",
  "fullConversationScript": "string — A COMPLETE, ready-to-use end-to-end sales conversation script that the sales rep can follow word-for-word from start to finish. This MUST be a flowing dialogue covering EVERY stage in order: (1) Opening & Introduction — greeting, name, company, reason for call, (2) Hook & Icebreaker — attention-grabbing statement to earn interest, (3) Discovery & Qualification — asking questions to understand needs, budget, timeline, decision-making, (4) Requirement Understanding — confirming and summarizing the prospect's pain points and goals, (5) Solution Presentation — presenting the product/service as the answer to their specific problems, (6) Objection Handling — addressing common objections with prepared responses, (7) Negotiation — discussing pricing, terms, and value, (8) Closing — clear call-to-action with next steps, (9) Follow-up — what to say if they need time or say no. Each stage should have the EXACT lines the sales rep should say, marked with [REP:] prefix, and predicted prospect responses marked with [PROSPECT:] prefix. Write in natural, conversational tone — not robotic or generic. Include stage transitions like '(pause for response)', '(listen actively)', '(acknowledge their point)'. This script must be self-contained and usable without any other material. Minimum 800 words.",
  "sections": [
    {
      "type": "string — one of: ${sectionTypes}",
      "title": "string",
      "content": "string — 2-5 sentences of natural dialogue specific to this script",
      "order": "number starting from 0",
      "isRequired": "boolean",
      "tips": ["1-3 practical delivery tips"]
    }
  ],
  "qualificationQuestions": [
    {
      "question": "string",
      "purpose": "string",
      "followUpIfYes": "string",
      "followUpIfNo": "string",
      "order": "number starting from 0"
    }
  ],
  "objectionResponses": [
    {
      "objection": "string — the common objection",
      "response": "string — how to respond, 2-3 sentences",
      "trustBuildingLine": "string",
      "ctaSuggestion": "string",
      "order": "number starting from 0"
    }
  ],
  "callExamples": ["2-3 example phrases or transitions a rep can actually say in this specific scenario"],
  "conversationBranches": [
    {
      "trigger": "string — the prospect's likely response or objection in this scenario",
      "response": "string — how to respond, 1-2 sentences specific to this branch",
      "nextSection": "string — which section type to go to next, one of: ${sectionTypes}",
      "order": "number starting from 0"
    }
  ],
  "trainingNotes": "string — 2-3 sentences of training guidance specific to this script type",
  "bestPractices": ["3-5 practical best practices for this script type and channel"],
  "coachingNotes": "string — 1-2 sentences of coaching advice for this scenario"
}

COMPLETENESS REQUIREMENTS:
- Every field in the schema MUST be populated — no empty strings, no null values, no omitted fields.
- Every qualification question MUST have all 4 sub-fields filled (question, purpose, followUpIfYes, followUpIfNo).
- Every objection response MUST have all 4 sub-fields filled (objection, response, trustBuildingLine, ctaSuggestion).
- Every conversation branch MUST have all 3 sub-fields filled (trigger, response, nextSection).
- Every section MUST have meaningful content of at least 2-3 sentences, not generic filler.
- The fullConversationScript MUST be a comprehensive, stage-by-stage conversation covering ALL stages from opening through follow-up. It must be at least 800 words and include exact dialogue with [REP:] and [PROSPECT:] prefixes.

Generate exactly 1 script. Include 5-7 sections, 3-5 qualification questions, 3-5 objection responses, and 3-5 conversation branches.`;

  // Build user prompt with custom instructions if provided
  let userPrompt = `Generate a complete sales script using the "${angle.name}" sales angle for:\n\n${buildCompanyContext(inputs)}`;

  // Append custom instructions if provided
  if (inputs.customInstructions && inputs.customInstructions.trim()) {
    userPrompt += `\n\nCUSTOM INSTRUCTIONS FROM USER:\n${inputs.customInstructions.trim()}`;
  }

  return { systemPrompt, userPrompt, maxTokens: 16000 };
}