/**
 * WhatsApp Nurturing AI Prompts
 * Prompt builders for sequence planning, message generation, optimization, and multi-channel assets
 */

import type { IWhatsAppCampaign, IWhatsAppSequencePlan, IWhatsAppNurturingMessage } from '../../models/WhatsAppCampaign';

// ============================================
// MESSAGE LENGTH LIMITS (single source of truth)
// ============================================

/** Target length the AI should aim for — concise, WhatsApp-friendly copy. */
export const WHATSAPP_MESSAGE_TARGET_CHARS = 300;
/** Absolute hard ceiling — no generated message may ever exceed this. */
export const WHATSAPP_MESSAGE_MAX_CHARS = 500;

/**
 * Safeguard that guarantees a message never exceeds the hard character ceiling.
 *
 * This is a last-resort clamp applied AFTER generation — the prompt is the
 * primary control, this only fires when the model overshoots. It trims at a
 * natural boundary (line break → sentence end → word) so the result stays
 * readable and grammatically complete instead of cutting mid-word.
 */
export function enforceWhatsAppMessageLength(
  copy: string,
  maxChars: number = WHATSAPP_MESSAGE_MAX_CHARS
): string {
  if (typeof copy !== 'string') return copy;
  const trimmed = copy.trim();
  if (trimmed.length <= maxChars) return trimmed;

  // Work within the allowed window, then back off to the last clean boundary.
  const window = trimmed.slice(0, maxChars);

  // Prefer the last complete line, then the last complete sentence, then the
  // last whole word — whichever preserves the most meaning without dangling.
  const lastLineBreak = window.lastIndexOf('\n');
  const lastSentence = Math.max(
    window.lastIndexOf('. '),
    window.lastIndexOf('! '),
    window.lastIndexOf('? '),
    window.lastIndexOf('\n')
  );
  const lastSpace = window.lastIndexOf(' ');

  let cut: number;
  if (lastSentence >= maxChars * 0.6) {
    // +1 keeps the terminating punctuation (". ", "! ", "? ").
    cut = lastSentence + 1;
  } else if (lastLineBreak >= maxChars * 0.5) {
    cut = lastLineBreak;
  } else if (lastSpace > 0) {
    cut = lastSpace;
  } else {
    cut = maxChars;
  }

  return window.slice(0, cut).trim();
}

// ============================================
// CONTEXT ASSEMBLY
// ============================================

/**
 * Builds a rich context string from selected data sources for AI generation.
 * Fetches relevant business data and formats it for the AI prompt.
 */
export function buildContextString(dataSources: string[], companyData: Record<string, any>): string {
  const sections: string[] = [];

  if (dataSources.includes('business-profile') && companyData.businessProfile) {
    const bp = companyData.businessProfile;
    sections.push(`## Business Profile
Company: ${bp.name || 'N/A'}
Industry: ${bp.industry || 'N/A'}
Mission: ${bp.mission || 'N/A'}
Vision: ${bp.vision || 'N/A'}
USP: ${bp.usp || 'N/A'}
Description: ${bp.description || 'N/A'}`);
  }

  if (dataSources.includes('founder') && companyData.founders?.length > 0) {
    sections.push(`## Founders
${companyData.founders.map((f: any) => `- ${f.name} (${f.designation || 'N/A'}): ${f.bio || f.expertise || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('product') && companyData.products?.length > 0) {
    sections.push(`## Products/Services
${companyData.products.map((p: any) => `- ${p.name}: ${p.description || p.usp || 'N/A'} (Price: ${p.price || 'N/A'})`).join('\n')}`);
  }

  if (dataSources.includes('icp') && companyData.icps?.length > 0) {
    sections.push(`## Ideal Customer Profiles
${companyData.icps.map((i: any) => `- ${i.name || i.industry || 'ICP'}: ${i.description || i.painPoints || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('persona') && companyData.personas?.length > 0) {
    sections.push(`## Buyer Personas
${companyData.personas.map((p: any) => `- ${p.name || p.jobTitle || 'Persona'}: ${p.description || p.challenges || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('competitor') && companyData.competitors?.length > 0) {
    sections.push(`## Competitors
${companyData.competitors.map((c: any) => `- ${c.name || 'Competitor'}: ${c.description || c.strengths || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('brand') && companyData.brand) {
    const b = companyData.brand;
    sections.push(`## Brand Strategy
Voice: ${b.brandVoice || 'N/A'}
Personality: ${b.brandPersonality || 'N/A'}
Values: ${b.brandValues || 'N/A'}
Positioning: ${b.brandPositioning || 'N/A'}`);
  }

  if (dataSources.includes('testimonial') && companyData.testimonials?.length > 0) {
    sections.push(`## Testimonials
${companyData.testimonials.map((t: any) => `- "${t.quote || t.content || 'N/A'}" — ${t.author || t.customerName || 'Customer'} (${t.rating || ''} stars)`).join('\n')}`);
  }

  if (dataSources.includes('case-study') && companyData.caseStudies?.length > 0) {
    sections.push(`## Case Studies
${companyData.caseStudies.map((c: any) => `- ${c.title || c.name || 'Case Study'}: Challenge: ${c.challenge || 'N/A'}, Solution: ${c.solution || 'N/A'}, Results: ${c.results || c.outcomes || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('faq') && companyData.faqs?.length > 0) {
    sections.push(`## Frequently Asked Questions
${companyData.faqs.map((f: any) => `- Q: ${f.question || 'N/A'} | A: ${f.answer || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('blog') && companyData.blogs?.length > 0) {
    sections.push(`## Blog Content
${companyData.blogs.slice(0, 5).map((b: any) => `- ${b.title || 'Blog Post'}: ${b.excerpt || b.metaDescription || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('landing-page') && companyData.landingPages?.length > 0) {
    sections.push(`## Landing Pages
${companyData.landingPages.slice(0, 3).map((l: any) => `- ${l.title || l.pageTitle || 'Landing Page'}: ${l.headline || l.valueProposition || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('courses') && companyData.courses?.length > 0) {
    sections.push(`## Courses
${companyData.courses.slice(0, 5).map((c: any) => `- ${c.title || c.name || 'Course'}: ${c.description || c.shortDescription || 'N/A'}`).join('\n')}`);
  }

  if (dataSources.includes('events') && companyData.events?.length > 0) {
    sections.push(`## Events
${companyData.events.slice(0, 5).map((e: any) => `- ${e.title || e.name || 'Event'}: ${e.description || e.shortDescription || 'N/A'}`).join('\n')}`);
  }

  return sections.join('\n\n');
}

// ============================================
// SEQUENCE PLAN PROMPT
// ============================================

export function buildSequencePlanPrompt(campaign: Partial<IWhatsAppCampaign>, contextString: string): string {
  const frameworkDescriptions: Record<string, string> = {
    'educational': 'Educational Nurturing: Educate → Build Trust → Offer Solution → CTA. Start with valuable content, establish authority, then present your solution.',
    'problem-solution': 'Problem-Solution Framework: Problem → Pain → Solution → CTA. Highlight the audience\'s pain points, agitate the problem, then offer your solution as the answer.',
    'storytelling': 'Storytelling Framework: Hook → Story → Lesson → CTA. Open with an engaging hook, tell a relevant story, extract a lesson, then call to action.',
    'founder-authority': 'Founder Authority Framework: Founder Insight → Experience → Trust Building → CTA. Share founder wisdom and personal experiences to build authority and trust.',
    'product-demonstration': 'Product Demonstration Framework: Problem → Feature → Benefit → CTA. Show the problem, demonstrate the product feature, highlight the benefit, then call to action.',
    'case-study': 'Case Study Framework: Challenge → Solution → Results → CTA. Present a real challenge, show the solution applied, share measurable results, then invite action.',
  };

  const hasContext = contextString && contextString.trim().length > 10;
  const contextSection = hasContext
    ? `## Business Context — USE THIS DATA IN YOUR PLAN
You MUST reference specific details from this context in your themes and objectives. Do NOT write generic themes — make every day's theme and objective specific to this business, its audience, its products, and its market position.

${contextString}`
    : `## Business Context
No specific business context provided. Create themes that are specific to the campaign goals and framework, using realistic placeholder references.`;

  const descriptionSection = campaign.description
    ? `\n## Campaign Brief / Instructions
${campaign.description}\nUse this brief to tailor the themes, objectives, and messaging angles. Every theme should directly reflect the strategic intent described in this brief.`
    : '';

  return `You are an expert WhatsApp marketing strategist creating a UNIQUE, PERSONALIZED nurturing sequence for a specific business.

## Campaign Details
- **Name**: ${campaign.name || 'Untitled Campaign'}
- **Goals**: ${(campaign.goals && campaign.goals.length > 0) ? campaign.goals.join(', ') : 'lead-nurturing'}
- **Duration**: ${campaign.sequenceDuration || 7} days
- **Frequency**: ${campaign.messageFrequency || 'daily'}
- **Framework**: ${(campaign.frameworks && campaign.frameworks.length > 0) ? campaign.frameworks.map(f => `${f} — ${frameworkDescriptions[f] || f}`).join('; ') : `educational — ${frameworkDescriptions['educational']}`}
- **Tone**: ${campaign.tone || 'friendly'}
- **Personalization Level**: ${campaign.personalizationLevel || 'medium'}
- **Language**: ${campaign.language || 'en'}
- **Target Region**: ${campaign.targetRegion || 'global'}
${descriptionSection}

${contextSection}

## CRITICAL INSTRUCTIONS — ANTI-TEMPLATE RULES
- Do NOT use generic themes like "Day 1: Introduction", "Day 2: Value", "Day 3: CTA" — these are too vague.
- Each theme MUST reference something SPECIFIC from the business context: a product name, an ICP pain point, a founder's insight, a case study result, a competitor weakness, etc.
- Each objective must be a concrete, measurable goal tied to the business (e.g., "Highlight how [Product] solves [ICP pain point]" rather than "Build trust").
- The messageAngle should describe the psychological approach specifically for THIS business's audience, not a generic marketing angle.
- The contentApproach must reference specific data sources (e.g., "Share the [Case Study] result of 3x ROI" not "Share a success story").
- If the Business Context section contains ICPs, personas, products, testimonials, or case studies, your themes MUST directly reference them by name or detail.

Generate a ${campaign.sequenceDuration || 7}-day WhatsApp nurturing sequence plan following the "${(campaign.frameworks && campaign.frameworks.length > 0) ? campaign.frameworks[0] : 'educational'}" framework.

For each day, provide:
1. **day**: The day number (1 to ${campaign.sequenceDuration || 7})
2. **theme**: A SPECIFIC theme name tied to the business context (NOT generic like "Introduction" or "Value Delivery")
3. **objective**: A specific, measurable goal referencing business details (1-2 sentences)
4. **messageAngle**: A specific psychological angle tailored to the target audience from the context
5. **contentApproach**: Specific content approach referencing named data sources (products, case studies, testimonials, etc.)

Ensure the sequence:
- Follows the "${(campaign.frameworks && campaign.frameworks.length > 0) ? campaign.frameworks[0] : 'educational'}" framework stages naturally
- Builds trust progressively from soft value to hard CTA
- Creates urgency toward the end using specific business differentiators
- Has a clear CTA trajectory from soft to hard
- Is appropriate for the "${campaign.tone}" tone
- Is personalized at the "${campaign.personalizationLevel}" level
- Is UNIQUE to this business — someone reading the themes should immediately know WHICH company this is for

Return ONLY a JSON array of objects with keys: day, theme, objective, messageAngle, contentApproach.`;
}

// ============================================
// MESSAGE GENERATION PROMPT
// ============================================

export function buildMessageGenerationPrompt(
  campaign: Partial<IWhatsAppCampaign>,
  sequencePlan: IWhatsAppSequencePlan[],
  contextString: string,
  dayRange?: { start: number; end: number }
): string {
  const planToUse = dayRange
    ? sequencePlan.filter((d) => d.day >= dayRange.start && d.day <= dayRange.end)
    : sequencePlan;

  const hasContext = contextString && contextString.trim().length > 10;
  const contextSection = hasContext
    ? `## Business Context — YOU MUST USE THIS DATA IN EVERY MESSAGE
This is the MOST IMPORTANT section. Every single message MUST reference specific details from this context. Do NOT write generic messages that could apply to any business — make each message uniquely tied to this business.

${contextString}`
    : `## Business Context
No specific business context provided. Write messages that are specific to the campaign goals, using realistic references to the business.`;

  const descriptionSection = campaign.description
    ? `\n## Campaign Brief / Instructions
${campaign.description}\nEvery message must align with this brief. Reference specific goals, target audience details, and messaging priorities from this brief.`
    : '';

  const icpSection = (campaign as any).targetIcpIds?.length
    ? `\n## Target ICPs
The following ICP IDs are specifically targeted: ${(campaign as any).targetIcpIds.join(', ')}. Ensure your messages speak directly to these ICPs' pain points, goals, and characteristics as described in the Business Context.`
    : '';

  const personaSection = (campaign as any).targetPersonaIds?.length
    ? `\n## Target Personas
The following persona IDs are specifically targeted: ${(campaign as any).targetPersonaIds.join(', ')}. Ensure your messages resonate with these personas' demographics, behaviors, and preferred communication styles as described in the Business Context.`
    : '';

  return `You are an expert WhatsApp copywriter creating UNIQUE, PERSONALIZED messages for a specific business's nurturing campaign. Every message MUST feel like it was written specifically for this business — not copied from a template.

## Campaign Details
- **Name**: ${campaign.name || 'Untitled Campaign'}
- **Goals**: ${(campaign.goals && campaign.goals.length > 0) ? campaign.goals.join(', ') : 'lead-nurturing'}
- **Tone**: ${campaign.tone || 'friendly'}
- **Personalization Level**: ${campaign.personalizationLevel || 'medium'}
- **Language**: ${campaign.language || 'en'}
- **Target Region**: ${campaign.targetRegion || 'global'}
- **Delivery Time**: ${campaign.deliveryTime || '09:00'}
${descriptionSection}${icpSection}${personaSection}

${contextSection}

## Sequence Plan
${planToUse.map((day) => `Day ${day.day}: ${day.theme} — ${day.objective} (Angle: ${day.messageAngle})`).join('\n')}

## CRITICAL REQUIREMENTS — ANTI-TEMPLATE RULES

### 🚫 DO NOT WRITE GENERIC MESSAGES
Every message MUST be unique to this specific business. Do NOT write messages that could apply to ANY company. Instead:
- Reference specific product names, features, and benefits from the Business Context
- Mention specific pain points from the ICPs and personas
- Quote or reference specific testimonials, case study results, or founder insights
- Use specific industry terminology from the Business Profile
- Reference specific competitor differentiators
- Include specific brand voice characteristics from the Brand Strategy

### CHARACTER LIMIT: TARGET ~${WHATSAPP_MESSAGE_TARGET_CHARS} CHARACTERS — HARD MAXIMUM ${WHATSAPP_MESSAGE_MAX_CHARS}
- Aim for around ${WHATSAPP_MESSAGE_TARGET_CHARS} characters per message — this is the sweet spot for WhatsApp
- The "copy" field must NEVER exceed ${WHATSAPP_MESSAGE_MAX_CHARS} characters under any circumstances
- Count characters carefully - shorter is always better
- Short, punchy messages perform best on WhatsApp
- Get straight to the point: no long intros, no repetition, no verbose explanations, no filler

### Format: Short Sentences with Line Breaks
- Write 2-4 SHORT sentences maximum
- Each sentence on a NEW LINE (use \\n for line breaks)
- Do NOT write paragraphs or long blocks of text
- Format: Line 1\\nLine 2\\nLine 3\\nCTA

### Example Format:
"Hey {{firstName}}! 👋\\nQuick question for you.\\nWhat's your biggest challenge with [topic]?\\nReply and let me know!"

## Instructions
Generate a WhatsApp message for each day in the sequence plan above. For each message, provide:

1. **id**: A unique identifier like "msg-{day}-{timestamp}"
2. **day**: The day number
3. **timeSlot**: "${campaign.deliveryTime || '09:00'}"
4. **goal**: Brief goal of this message (max 50 characters) — must reference specific business context
5. **copy**: The WhatsApp message text. TARGET ~${WHATSAPP_MESSAGE_TARGET_CHARS} CHARS, NEVER exceed ${WHATSAPP_MESSAGE_MAX_CHARS}. Use short sentences with line breaks (\\n). Use personalization variables like {{firstName}}, {{companyName}}, {{productName}} where appropriate. MUST reference specific details from the Business Context.
6. **cta**: A clear call-to-action (e.g., "Reply YES", "Book call", "Learn more")
7. **ctaUrl**: Optional URL for the CTA (leave empty if not applicable)
8. **personalizationVariables**: Array of variable names used (e.g., ["firstName", "companyName"])
9. **contentBlocks**: Empty array [] - we don't need content blocks

## WhatsApp Copy Guidelines
- Use conversational, natural language (like texting a friend)
- Include 1-2 emojis maximum, placed naturally
- Start with a hook that grabs attention
- Keep it PERSONAL - use {{firstName}} often
- Each line should be short and readable (under 50 characters preferred)
- End with a clear, single CTA
- Never use overly salesy language in early days
- Build trust before selling
- Match the "${campaign.tone}" tone consistently
- REMEMBER: aim for ~${WHATSAPP_MESSAGE_TARGET_CHARS} characters and NEVER exceed ${WHATSAPP_MESSAGE_MAX_CHARS} for the "copy" field

## PERSONALIZATION BY LEVEL
- **basic**: Use {{firstName}} in greeting. Reference the company name.
- **medium**: Use {{firstName}}, {{companyName}}. Reference specific ICP pain points, product features, and business context.
- **advanced**: Use {{firstName}}, {{companyName}}, {{productName}}, {{industry}}. Tailor each message to specific ICP characteristics, persona behaviors, and funnel stage. Reference testimonials, case studies, and competitor differentiators by name.

## WHAT TO AVOID (TEMPLATE SMELL)
- ❌ "Hey! Just checking in." — too generic
- ❌ "Here's something you might find interesting." — no specificity
- ❌ "Let me know if you'd like to learn more." — weak, template CTA
- ❌ "We help businesses like yours succeed." — meaningless without context
- ❌ Writing the same message structure every day with only the day number changing

## WHAT TO DO (CONTEXT-RICH)
- ✅ "Hey {{firstName}}! 👋\\nSaw you're in [industry] — [specific pain point] is huge there.\\nWe helped [client] cut [metric] by [number].\\nWant the playbook?"
- ✅ "{{firstName}}, quick stat:\\n[Specific number]% of [industry] struggle with [pain point].\\n[Product] tackles exactly that.\\nSee how → [link]"
- ✅ Use the EXACT names of products, features, and benefits from the Business Context
- ✅ Reference specific testimonials ("Sarah from [Company] said...") and case study results
- ✅ Each message should feel like a different conversation, not the same template with swapped names

Return ONLY a JSON array of message objects with the above structure. Remember: "copy" should be ~${WHATSAPP_MESSAGE_TARGET_CHARS} characters and MUST NEVER exceed ${WHATSAPP_MESSAGE_MAX_CHARS} characters.`;
}

// ============================================
// OPTIMIZATION PROMPT
// ============================================

export function buildOptimizationPrompt(
  campaign: Partial<IWhatsAppCampaign>,
  messages: IWhatsAppNurturingMessage[]
): string {
  return `You are an expert WhatsApp marketing optimizer. Analyze the following WhatsApp nurturing sequence and provide optimization suggestions.

## Campaign Details
- **Goals**: ${(campaign.goals && campaign.goals.length > 0) ? campaign.goals.join(', ') : 'lead-nurturing'}
- **Tone**: ${campaign.tone || 'friendly'}
- **Framework**: ${(campaign.frameworks && campaign.frameworks.length > 0) ? campaign.frameworks.join(', ') : 'educational'}
- **Duration**: ${campaign.sequenceDuration || 7} days
- **Messages**: ${messages.length} total

## Current Messages
${messages.map((m) => `Day ${m.day} [${m.goal}]: "${m.copy.substring(0, 100)}..." | CTA: "${m.cta}"`).join('\n')}

## Instructions
Analyze each message and the overall sequence for:

1. **Open Rate Optimization**: Are the opening lines compelling? Do they create curiosity?
2. **Response Rate Optimization**: Are the CTAs clear and easy to respond to?
3. **Engagement Score**: Is the content varied enough to maintain interest?
4. **Conversion Probability**: Does the sequence build toward the goal effectively?

For each category, provide a score from 0-100 and specific suggestions.

Return a JSON object with:
- openRateScore: number (0-100)
- responseRateScore: number (0-100)
- engagementScore: number (0-100)
- conversionScore: number (0-100)
- suggestions: array of specific, actionable improvement suggestions (max 10)
- optimizedCopy: optional improved version of the overall sequence approach (1-2 sentences)`;
}

// ============================================
// SINGLE MESSAGE REGENERATION PROMPT
// ============================================

export function buildRegenerateMessagePrompt(
  campaign: Partial<IWhatsAppCampaign>,
  message: IWhatsAppNurturingMessage,
  dayPlan?: IWhatsAppSequencePlan
): string {
  const descriptionSection = campaign.description
    ? `\n## Campaign Brief\n${campaign.description}`
    : '';

  return `You are an expert WhatsApp copywriter. Regenerate a single WhatsApp nurturing message with improved, PERSONALIZED copy that is specific to this business — NOT a generic template.

## Campaign Context
- **Goals**: ${(campaign.goals && campaign.goals.length > 0) ? campaign.goals.join(', ') : 'lead-nurturing'}
- **Tone**: ${campaign.tone || 'friendly'}
- **Personalization Level**: ${campaign.personalizationLevel || 'medium'}
- **Day**: ${message.day} of ${campaign.sequenceDuration || 7}
${descriptionSection}

## Current Message
- **Goal**: ${message.goal}
- **Copy**: ${message.copy}
- **CTA**: ${message.cta}

${dayPlan ? `## Day Plan\nTheme: ${dayPlan.theme}\nObjective: ${dayPlan.objective}\nAngle: ${dayPlan.messageAngle}` : ''}

## CRITICAL REQUIREMENTS

### ANTI-TEMPLATE RULE
The regenerated message MUST be unique and specific to this business. Do NOT write generic marketing copy. Reference specific products, features, pain points, testimonials, or business details wherever possible.

### Character Limit: TARGET ~${WHATSAPP_MESSAGE_TARGET_CHARS} CHARACTERS — HARD MAXIMUM ${WHATSAPP_MESSAGE_MAX_CHARS}
- Aim for around ${WHATSAPP_MESSAGE_TARGET_CHARS} characters
- The "copy" field must NEVER exceed ${WHATSAPP_MESSAGE_MAX_CHARS} characters
- Count characters carefully - shorter is always better

### Format: Short Sentences with Line Breaks
- Write 2-4 SHORT sentences maximum
- Each sentence on a NEW LINE (use \\n for line breaks)
- Do NOT write paragraphs or long blocks of text
- Format: Line 1\\nLine 2\\nLine 3\\nCTA

### Example Format:
"Hey {{firstName}}! 👋\\nQuick question for you.\\nWhat's your biggest challenge?\\nReply and let me know!"

## Instructions
Rewrite the message to be more engaging, personal, and effective. Improve:
1. Opening hook - grab attention with a specific reference to the business or pain point
2. Body content - short, punchy lines that reference specific product features or benefits
3. CTA clarity - make it easy and specific (not "let me know" but "reply YES for the [Product] guide")
4. Personalization - use {{firstName}}, {{companyName}}, {{productName}}, etc.
5. Specificity - reference real details about this business's offerings, customers, or market

Return ONLY a JSON object with keys: id, day, timeSlot, goal, copy, cta, ctaUrl, personalizationVariables, contentBlocks, status.

Remember: "copy" should be ~${WHATSAPP_MESSAGE_TARGET_CHARS} characters and MUST NEVER exceed ${WHATSAPP_MESSAGE_MAX_CHARS} characters.`;
}

// ============================================
// MULTI-CHANNEL PROMPT
// ============================================

export function buildMultiChannelPrompt(
  campaign: Partial<IWhatsAppCampaign>,
  messages: IWhatsAppNurturingMessage[],
  channel: 'email' | 'landing-page' | 'social-post' | 'ad-copy'
): string {
  const channelGuidance: Record<string, string> = {
    'email': 'Create an email sequence that mirrors the WhatsApp nurturing flow. Include subject lines, preview text, and body copy.',
    'landing-page': 'Create a landing page that captures leads for the WhatsApp sequence. Include headline, subheadline, body copy, CTA, and social proof.',
    'social-post': 'Create social media posts that drive awareness and sign-ups for the WhatsApp sequence. Include post copy and hashtags.',
    'ad-copy': 'Create ad copy (for Meta/Google) that drives traffic to the WhatsApp opt-in. Include headlines, descriptions, and CTAs.',
  };

  return `You are an expert multi-channel marketer. Create matching ${channel} assets for a WhatsApp nurturing campaign.

## Campaign Details
- **Name**: ${campaign.name || 'Untitled Campaign'}
- **Goals**: ${(campaign.goals && campaign.goals.length > 0) ? campaign.goals.join(', ') : 'lead-nurturing'}
- **Tone**: ${campaign.tone || 'friendly'}
- **Key Messages**: ${messages.slice(0, 3).map((m) => m.goal).join(', ')}

## Instructions
${channelGuidance[channel]}

Return ONLY a JSON object with keys: id, channel, subject (for email), headline, copy, cta, status.`;
}