/**
 * Speaking Engagement AI Prompts
 * Typed input interfaces and prompt builders for each speech type
 */

// ============================================
// INPUT INTERFACES
// ============================================

export interface SpeakingEngagementInputs {
  // Company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyMission?: string;
  companyVision?: string;
  companyCoreValues?: string[];
  companyUsp?: string;
  companyProducts?: string[];
  companyAchievements?: string[];
  companyAwards?: string[];

  // Speaker profile data
  speakerType: string;
  speakerName?: string;
  speakerPosition?: string;
  speakerCompanyName?: string;
  speakerDepartment?: string;
  speakerIndustry?: string;
  speakerBio?: string;
  speakerExpertise?: string[];

  // Generation options
  speechType: string;
  audienceType?: string;
  language: string;
  duration: string;
  tone: string;
  topic?: string;
  occasionContext?: string;
  additionalNotes?: string;

  // Harmony context
  harmonyText?: string;

  // Control
  targetCount: number;

  // Anti-repetition: 1-line summaries of previously used story hooks
  usedStoryHooks?: string[];
}

export interface SpeakingEngagementOutput {
  name: string;
  speechType: string;
  audienceType: string;
  language: string;
  duration: string;
  speakerType: string;
  tone: string;
  content: string;
  structure?: {
    opening: string;
    hook: string;
    story: string;
    mainMessage: string;
    conclusion: string;
    callToAction: string;
  };
  speakerNotes?: {
    deliveryGuidance: string[];
    emphasisPoints: string[];
    pausePoints: string[];
    audienceEngagement: string[];
  };
  stageInstructions?: {
    pausePoints: { timestamp: string; instruction: string }[];
    emphasisPoints: { phrase: string; intensity: 'light' | 'moderate' | 'strong' }[];
    audienceEngagementMoments: { moment: string; technique: string }[];
  };
  confidenceTips?: {
    deliverySuggestions: string[];
    bodyLanguageTips: string[];
    vocalVariationTips: string[];
  };
  specialOutputs?: Record<string, string | string[]>;
  status: string;
}

// ============================================
// SPEECH TYPE CONFIGURATIONS
// ============================================

const SPEECH_TYPE_LABELS: Record<string, string> = {
  'tedx-speech': 'TEDx Speech',
  'josh-talks-speech': 'Josh Talks Speech',
  'one-line-speech': 'One-Line Speech',
  'storytelling-speech': 'Storytelling Speech',
  'elevator-pitch': 'Elevator Pitch',
  'keynote-speech': 'Keynote Speech',
  'event-speech': 'Event Speech',
  'motivational-speech': 'Motivational Speech',
  'company-introduction': 'Company Introduction Speech',
  'founder-introduction': 'Founder Introduction Speech',
  'employee-introduction': 'Employee Introduction Speech',
  'product-launch-speech': 'Product Launch Speech',
  'award-acceptance': 'Award Acceptance Speech',
  'investor-pitch-speech': 'Investor Pitch Speech',
  'networking-introduction': 'Networking Introduction',
  'wikipedia-article': 'Wikipedia Article',
  'google-knowledge-panel': 'Google Knowledge Panel',
  'custom-speech': 'Custom Speech',
};

const SPEECH_TYPE_PROMPTS: Record<string, string> = {
  'tedx-speech': `You are crafting a TEDx-style speech. TEDx speeches are built on the principle of "ideas worth spreading." The speech MUST include:
- A POWERFUL OPENING: Start with a startling statistic, provocative question, or unexpected statement that immediately grabs attention
- A PERSONAL STORY: Share an authentic, vulnerable story that humanises the speaker and connects to the core idea
- A TRANSFORMATION JOURNEY: Show the before → during → after arc — how the speaker or their subject changed
- A LESSON LEARNED: Distil the experience into ONE clear, memorable takeaway
- AN ACTIONABLE TAKEAWAY: Give the audience something specific they can DO, not just think about
- A TEDx-STYLE ENDING: Circle back to the opening hook for a satisfying callback, end with a call to action that inspires

The tone should feel intimate and conversational, as if speaking to a friend. Use "I" and "you" frequently. Avoid jargon. Make every sentence earn its place.`,

  'josh-talks-speech': `You are crafting a Josh Talks-style speech — an inspiring, emotionally powerful talk built on personal storytelling. Josh Talks speeches connect deeply with everyday people through authentic, relatable narratives. The speech MUST include:
- RELATABLE OPENING: Start with a situation the audience can instantly relate to — struggles with expectations, financial hardship, social pressure, or personal doubt
- THE STRUGGLE: Describe challenges vividly with emotional honesty — the failures, rejections, and doubts
- THE CHALLENGE: What seemed impossible to overcome — social barriers, lack of resources, systemic obstacles
- THE BREAKTHROUGH: The turning point moment — a decision, an opportunity, a realisation that changed everything
- THE SUCCESS: What happened after the breakthrough — tangible results and personal growth
- THE INSPIRATION: End with an uplifting message that motivates the audience to take their own step forward

Use simple, powerful language. If the target language is Hindi or an Indian language, mix it naturally with local expressions. Reference cultural contexts authentically. The emotion should build progressively from struggle to triumph.`,

  'one-line-speech': `You are crafting one-line speech statements — concise, powerful, memorable single sentences that capture the essence of a message. Generate FOUR versions:
- PROFESSIONAL VERSION: Formal, corporate-appropriate, conveys expertise and credibility
- MOTIVATIONAL VERSION: Inspiring and uplifting, energises the listener to take action
- EMOTIONAL VERSION: Touches the heart, creates an emotional connection and empathy
- IMPACT VERSION: Bold and thought-provoking, leaves a lasting impression

Each version must be ONE sentence maximum. Every word must earn its place. The statements should be quotable, memorable, and instantly convey who the speaker is and what they stand for.`,

  'storytelling-speech': `You are crafting a storytelling speech built on the classic 5-act narrative structure. The speech MUST include:
- BEGINNING: Set the scene with vivid sensory details — time, place, atmosphere, characters. Make the audience SEE the world you're describing
- CONFLICT: Introduce the central tension or challenge. What went wrong? What obstacle appeared? Create genuine uncertainty about the outcome
- TURNING POINT: The decisive moment when everything changes — a decision, a revelation, an unexpected event that shifts the trajectory
- RESOLUTION: How the conflict resolves. Show the result through action, not just telling. What did the characters DO?
- LESSON: The universal truth or insight this story reveals. Connect it to the audience's own lives

Use concrete details, dialogue, and sensory language. The audience should feel like they're watching a film, not hearing a report.`,

  'elevator-pitch': `You are crafting an elevator pitch — a concise, persuasive speech designed to spark interest in a brief encounter. Generate THREE versions:
- 30-SECOND VERSION: The hook — one compelling sentence about who you are and what problem you solve, ending with a question that invites conversation
- 60-SECOND VERSION: Hook + value proposition — add 1-2 sentences about your unique approach, a specific result or metric, and why it matters
- 90-SECOND VERSION: Hook + value + credibility — expand with a brief client/result story, a clear ask or next step, and a memorable closing line

Each version must be self-contained. The pitch should feel natural, not rehearsed. Use specific numbers and outcomes, not vague claims. End every version with something that invites the listener to ask "tell me more."`,

  'keynote-speech': `You are crafting a keynote speech — a signature presentation that sets the tone for an entire event. The speech MUST include:
- A GRAND OPENING: Command the room from the first moment — a bold statement, a powerful question, or a surprising revelation
- A COMPELLING NARRATIVE: Weave together data, stories, and insights into a cohesive argument or journey
- 3-5 KEY INSIGHTS: Each insight should be memorable, actionable, and connected to the overall theme. Use the rule of three for impact
- AUDIENCE ENGAGEMENT MOMENTS: Plan 2-3 moments where you directly address or involve the audience
- A VISIONARY CONCLUSION: Paint a picture of the future you're advocating for. Leave the audience with a clear sense of direction and purpose
- A MEMORABLE CLOSE: End with a phrase, question, or call-back that the audience will remember and repeat

The tone should be authoritative yet accessible. Use rhetorical devices (repetition, contrast, metaphor) strategically. Every section should build momentum toward the conclusion.`,

  'event-speech': `You are crafting an event speech — a formal address for a specific occasion (inauguration, farewell, celebration, commemoration). The speech MUST include:
- APPROPRIATE OPENING: Acknowledge the occasion, hosts, and audience with proper etiquette and warmth
- CONTEXT SETTING: Briefly explain the significance of the event and why everyone is gathered
- CORE MESSAGE: The main point or theme that connects to the occasion — honour, celebrate, inspire, or commemorate
- PERSONAL TOUCHES: Include 1-2 relevant personal anecdotes or observations that make the speech feel genuine
- FORWARD-LOOKING CONCLUSION: End with optimism, gratitude, or a call to action appropriate to the occasion

Match the formality level to the event type. Use inclusive language ("we", "our"). Acknowledge the context and audience explicitly. The speech should feel purposeful and appropriate to the specific occasion.`,

  'motivational-speech': `You are crafting a motivational speech — designed to ignite action and inspire change. The speech MUST include:
- AN ATTENTION-GRABBING OPENING: Start with a bold statement, surprising fact, or provocative question that makes the audience lean in
- A RELATABLE STRUGGLE: Describe challenges the audience faces — show you understand their pain, doubts, and obstacles
- A SHIFT IN PERSPECTIVE: Introduce a new way of seeing the situation — a reframe that turns obstacles into opportunities
- ACTIONABLE STEPS: Give 3-5 specific, concrete actions the audience can take TODAY, not someday
- AN EMPOWERING CLOSE: End with a declaration of belief in the audience, a challenge to act, and a vision of what's possible

Use short, punchy sentences for emphasis. Build energy progressively. Use "you" and "your" to make it personal. Every paragraph should make the audience feel more capable than the last one.`,

  'company-introduction': `You are crafting a company introduction speech — presenting an organisation to an audience. The speech MUST include:
- WHO WE ARE: A clear, memorable statement of what the company does and for whom
- OUR ORIGIN: Brief founding story that humanises the brand and shows authenticity
- WHAT MAKES US DIFFERENT: Unique value proposition, competitive advantages, or distinctive approach
- OUR IMPACT: Specific results, client stories, or data points that prove value
- OUR VISION: Where the company is heading and why it matters to the audience
- A CALL TO ENGAGE: Clear next step for the audience — visit, connect, partner, follow

Use confident, professional language. Lead with the audience's needs, not the company's features. Use specific numbers over vague superlatives. The tone should be proud but not arrogant — inviting, not selling.`,

  'founder-introduction': `You are crafting a founder introduction speech — presenting the person behind the company. The speech MUST include:
- A PERSONAL HOOK: Start with a moment, story, or realisation that led to founding the company
- THE PROBLEM WORTH SOLVING: Describe the gap in the market or the need that inspired the venture
- THE JOURNEY: Key milestones, pivots, and lessons from building the company — show resilience and vision
- THE TEAM AND CULTURE: Acknowledge the people who made it possible and the values that guide decisions
- THE VISION AHEAD: What drives the founder and where the company is going next
- A MEMORABLE CLOSING: A personal conviction or invitation that leaves a lasting impression

Be authentic and vulnerable — share failures, not just successes. Use "I" statements for personal conviction and "we" for team achievements. The audience should feel they know the person, not just the title.`,

  'employee-introduction': `You are crafting an employee introduction speech — introducing a team member or presenting oneself professionally. The speech MUST include:
- A WARM OPENING: Name, role, and a personal touch that makes the introduction feel genuine
- PROFESSIONAL BACKGROUND: Relevant experience and skills, told as a brief narrative not a resume list
- CURRENT FOCUS: What they're working on, excited about, or contributing to the organisation
- PERSONAL INTEREST: A genuine human detail — hobby, passion, or fun fact that makes them memorable
- VALUE PROPOSITION: How their skills and perspective benefit the team or audience
- A CONNECTING CLOSE: An invitation to connect, collaborate, or continue the conversation

Keep it concise and warm. Balance professional credentials with personal warmth. The goal is to make the audience want to know this person better.`,

  'product-launch-speech': `You are crafting a product launch speech — unveiling a new product with excitement and conviction. The speech MUST include:
- THE REVEAL MOMENT: Build anticipation, then unveil with clarity and impact
- THE PROBLEM: Describe the pain point or unmet need that the product addresses — make the audience feel it
- THE SOLUTION: Show how the product solves the problem, with specific features mapped to benefits
- THE PROOF: Data, testimonials, or demonstrations that validate the claims
- THE EXPERIENCE: Help the audience imagine using the product — sensory, emotional, practical details
- THE CALL TO ACTION: Clear next steps — how to get it, when it's available, what to do right now

Build energy throughout. Use "you" and "imagine" frequently. Show, don't just tell. The audience should feel like they're discovering something that will change their work or life for the better.`,

  'award-acceptance': `You are crafting an award acceptance speech — expressing gratitude with grace and humility. The speech MUST include:
- A GRACIOUS OPENING: Express genuine surprise and humility — this moment is about the recognition, not self-promotion
- GRATITUDE: Thank specific people and organisations who made this possible — mentors, team, family, partners
- THE JOURNEY: Briefly share what this achievement represents — the effort, setbacks, and growth behind it
- THE BIGGER PICTURE: Connect this moment to a larger purpose, cause, or community
- A FORWARD-LOOKING CLOSE: What this award means for the future — renewed commitment, next goals, or a promise to pay it forward

Be warm and authentic. Use self-deprecating humour sparingly. Keep gratitude specific — name names, mention moments. The tone should be humble but not dismissive of the achievement. Leave the audience feeling inspired, not just impressed.`,

  'investor-pitch-speech': `You are crafting an investor pitch speech — persuading investors to fund your venture. The speech MUST include:
- THE HOOK: Open with a compelling problem statement or market opportunity that demands attention
- THE PROBLEM: Define the pain point clearly with data — how big is it, who suffers, what's the cost of inaction
- THE SOLUTION: Present the product/service as the answer — how it works, why it's better, what makes it defensible
- TRACTION: Show evidence of demand — revenue, users, growth rate, partnerships, or validated learnings
- THE MARKET: TAM/SAM/SOM, competitive landscape, and why NOW is the right time
- THE ASK: Clear funding amount, use of funds, milestones the investment will achieve, and expected return
- THE TEAM: Why this team is uniquely positioned to win

Be data-driven and confident. Every claim should be backed by evidence. Lead with the opportunity, not the technology. Address risks proactively. The pitch should feel like an invitation to a compelling opportunity, not a request for help.`,

  'networking-introduction': `You are crafting a networking introduction — a brief, memorable way to introduce yourself in professional settings. The speech MUST include:
- A MEMORABLE HOOK: One sentence that makes people curious and want to learn more
- VALUE STATEMENT: What you do and who you help — framed as outcomes, not job titles
- RELEVANCE: A brief connection to the context — the event, the person, the shared interest
- CONVERSATION STARTER: A question or observation that naturally extends the introduction into a real conversation

Keep it under 30 seconds for casual settings, under 60 seconds for formal ones. Avoid jargon and titles — focus on impact and outcomes. The goal is to be memorable and invite further conversation, not to impress with credentials.`,

  'custom-speech': `You are crafting a custom speech tailored to the specific needs described by the user. Consider:
- The speaker's role, expertise, and personal style
- The audience's expectations, knowledge level, and what they need to hear
- The occasion's purpose, tone, and formality level
- The desired outcome — what should the audience think, feel, or do after hearing this speech?
- The available time — match content depth to duration

Craft a speech that feels authentic to the speaker while being perfectly suited to the audience and occasion. Include appropriate structure, tone, and delivery guidance.`,

  'wikipedia-article': `You are crafting a Wikipedia-style encyclopedic article. Wikipedia articles are neutral, well-sourced, and comprehensive. The article MUST include:
- INTRODUCTION: A concise overview paragraph that establishes notability and summarizes key facts
- EARLY LIFE & BACKGROUND: Relevant biographical or historical context that shaped the subject
- CAREER & ACHIEVEMENTS: Notable accomplishments, milestones, and contributions organized chronologically or thematically
- LEGACY & IMPACT: The subject's lasting influence, recognition, and significance in their field
- REFERENCES & SOURCES: Indicate where key claims would be sourced from

Maintain a strictly neutral point of view throughout. Avoid promotional language, puffery, or subjective claims without attribution. Use precise, factual language. Structure with clear section headers. Ensure every claim is verifiable.`,

  'google-knowledge-panel': `You are crafting a Google Knowledge Panel summary — the concise, factual information box that appears in search results. Knowledge panels are brief, authoritative, and scannable. The content MUST include:
- SUMMARY: A 2-3 sentence overview establishing who/what the subject is and why they are notable
- KEY FACTS: Essential data points — name, title/role, organisation, location, key dates
- NOTABLE ACHIEVEMENTS: 3-5 bullet points of the most significant accomplishments
- RELATED ENTITIES: Connections to organisations, people, or topics that provide context

Keep every section extremely concise and factual. No flowery language or opinions. Optimize for quick scanning — this is the kind of information someone reads in 30 seconds on a search results page. Use clear labels and structured formatting.`,
};

// ============================================
// PROMPT BUILDER FUNCTIONS
// ============================================

export function buildSpeakingEngagementPrompt(inputs: SpeakingEngagementInputs): { systemPrompt: string; userPrompt: string; maxTokens: number } {
  const speechTypeLabel = SPEECH_TYPE_LABELS[inputs.speechType] || inputs.speechType;
  const speechTypePrompt = SPEECH_TYPE_PROMPTS[inputs.speechType] || SPEECH_TYPE_PROMPTS['custom-speech'];

  const durationMap: Record<string, string> = {
    '30s': '30 seconds',
    '1min': '1 minute',
    '2min': '2 minutes',
    '3min': '3 minutes',
    '5min': '5 minutes',
    '10min': '10 minutes',
    '15min': '15 minutes',
    '20min': '20 minutes',
    '30min': '30 minutes',
    '45min': '45 minutes',
    '1hr': '1 hour',
    '2hr-plus': '2+ hours',
  };
  const durationLabel = durationMap[inputs.duration] || inputs.duration;

  const languageMap: Record<string, string> = {
    'en': 'English',
    'hi': 'Hindi',
    'mr': 'Marathi',
    'es': 'Spanish',
    'fr': 'French',
    'de': 'German',
    'pt': 'Portuguese',
    'it': 'Italian',
    'nl': 'Dutch',
    'ru': 'Russian',
    'ja': 'Japanese',
    'ko': 'Korean',
    'zh': 'Chinese (Mandarin)',
    'ar': 'Arabic',
    'tr': 'Turkish',
    'pl': 'Polish',
    'sv': 'Swedish',
    'no': 'Norwegian',
    'da': 'Danish',
    'fi': 'Finnish',
    'cs': 'Czech',
    'el': 'Greek',
    'he': 'Hebrew',
    'th': 'Thai',
    'vi': 'Vietnamese',
    'id': 'Indonesian',
    'ms': 'Malay',
    'fil': 'Filipino',
    'bn': 'Bengali',
    'ur': 'Urdu',
    'ta': 'Tamil',
    'te': 'Telugu',
    'kn': 'Kannada',
    'ml': 'Malayalam',
    'pa': 'Punjabi',
    'gu': 'Gujarati',
    'sw': 'Swahili',
    'am': 'Amharic',
  };
  const languageLabel = languageMap[inputs.language] || inputs.language || 'English';

  const toneMap: Record<string, string> = {
    'professional': 'professional and polished',
    'inspirational': 'inspirational and uplifting',
    'motivational': 'motivational and energising',
    'emotional': 'emotional and heartfelt',
    'humorous': 'humorous and light-hearted',
    'formal': 'formal and authoritative',
    'friendly': 'friendly and approachable',
    'corporate': 'corporate and strategic',
    'casual': 'casual and conversational',
    'storytelling': 'storytelling and narrative',
  };
  const toneLabel = toneMap[inputs.tone] || inputs.tone;

  // Build language instruction block — always explicit, never ambiguous
  const isNonEnglish = languageLabel !== 'English';
  const languageBlock = isNonEnglish
    ? `LANGUAGE REQUIREMENT (HIGHEST PRIORITY — STRICTLY ENFORCED): The target language is ${languageLabel}. You MUST write the ENTIRE output — every single word of the speech content, structure, speaker notes, stage instructions, confidence tips, and special outputs — ENTIRELY in ${languageLabel}. Do NOT write in English. Do NOT write in Hindi. Do NOT write in any language other than ${languageLabel}. Even proper nouns and brand names should be transliterated into ${languageLabel} script where possible. The ONLY English allowed is the JSON field names (e.g., "content", "structure", "speakerNotes"). All VALUES inside the JSON must be in ${languageLabel}. This overrides any default tendency to write in English, Hindi, or any other language. If you write in the wrong language, the output is completely useless.`
    : `LANGUAGE: Write in English.`;

  // Build system prompt
  let systemPrompt = `You are an expert speech writer and public speaking coach. You create compelling, authentic, and impactful speeches that sound natural and human — never generic, never AI-sounding.

${languageBlock}

OUTPUT FORMAT — CRITICAL:
You MUST respond with ONLY a valid JSON object. Do NOT include any thinking, reasoning, chain-of-thought, analysis, or explanatory text before or after the JSON. Do NOT write "Here is the JSON" or "Sure, let me create..." — output the JSON object directly starting with { and ending with }. No markdown code fences. No preamble. No commentary.

${speechTypePrompt}

CRITICAL RULES:
1. NEVER use clichés like "In today's fast-paced world" or "It's an honour to be here"
2. Make the speech SPECIFIC to the speaker, company, and context
3. Vary sentence length for rhythm and impact
4. Include specific details and stories — avoid vague generalisations
5. Sound like a real person, not a template
6. Tone: ${toneLabel}
7. Target duration: ${durationLabel}
8. Cut anything that doesn't advance the message`;

  // Add harmony context if available
  if (inputs.harmonyText) {
    systemPrompt += `\n\nBRAND VOICE AND CONTEXT:\n${inputs.harmonyText}`;
  }

  // CRITICAL LANGUAGE OVERRIDE — appended at the very end to prevent the LLM
  // defaulting to English or Hindi when the user selected a different language
  if (isNonEnglish) {
    systemPrompt += `\n\nFINAL REMINDER — LANGUAGE (NON-NEGOTIABLE): The target language is ${languageLabel}. The entire output must be in ${languageLabel}. Do NOT write in English. Do NOT write in Hindi. Do NOT write in any language other than ${languageLabel}. All speech content, speaker notes, stage instructions, confidence tips, and special outputs must be written in ${languageLabel}. Only the JSON keys (field names) remain in English. This is a strict, non-negotiable requirement. If you write in any language other than ${languageLabel}, the output will be rejected.`;
  }

  // Build user prompt
  let userPrompt = `Generate a ${speechTypeLabel} with the following details:

**Speaker Information:**
- Speaker Type: ${inputs.speakerType}
- Speaker Name: ${inputs.speakerName || 'Not specified'}
- Position: ${inputs.speakerPosition || 'Not specified'}
- Company: ${inputs.speakerCompanyName || 'Not specified'}`;

  if (inputs.speakerDepartment) {
    userPrompt += `\n- Department: ${inputs.speakerDepartment}`;
  }
  if (inputs.speakerIndustry) {
    userPrompt += `\n- Industry: ${inputs.speakerIndustry}`;
  }

  userPrompt += `

**Company Information:**
- Company: ${inputs.companyName || 'Not specified'}`;
  if (inputs.companyDescription) userPrompt += `\n- Description: ${inputs.companyDescription}`;
  if (inputs.companyIndustry) userPrompt += `\n- Industry: ${inputs.companyIndustry}`;
  if (inputs.companyMission) userPrompt += `\n- Mission: ${inputs.companyMission}`;
  if (inputs.companyVision) userPrompt += `\n- Vision: ${inputs.companyVision}`;
  if (inputs.companyUsp) userPrompt += `\n- USP: ${inputs.companyUsp}`;
  if (inputs.companyProducts?.length) userPrompt += `\n- Products/Services: ${inputs.companyProducts.join(', ')}`;
  if (inputs.companyAchievements?.length) userPrompt += `\n- Achievements: ${inputs.companyAchievements.join(', ')}`;
  if (inputs.companyAwards?.length) userPrompt += `\n- Awards: ${inputs.companyAwards.join(', ')}`;

  userPrompt += `

**Speech Configuration:**
- Speech Type: ${speechTypeLabel}
- Audience: ${inputs.audienceType || 'General audience'}
- Language: ${languageLabel}
- Duration: ${durationLabel}
- Tone: ${toneLabel}`;

  if (inputs.topic) userPrompt += `\n- Topic: ${inputs.topic}`;
  if (inputs.occasionContext) userPrompt += `\n- Occasion: ${inputs.occasionContext}`;
  if (inputs.additionalNotes) userPrompt += `\n- Additional Notes: ${inputs.additionalNotes}`;

  // Add special output requirements based on speech type
  userPrompt += `

**Required Output Structure:**
Respond with a valid JSON object with these fields:
{
  "name": "A descriptive name for this speech",
  "content": "The complete speech text, properly formatted with paragraphs",
  "structure": {
    "opening": "The opening section of the speech",
    "hook": "The attention-grabbing hook",
    "story": "The narrative or story section",
    "mainMessage": "The core message or argument",
    "conclusion": "The concluding section",
    "callToAction": "The specific call to action"
  },
  "speakerNotes": {
    "deliveryGuidance": ["3-5 specific delivery tips for this speech"],
    "emphasisPoints": ["3-5 phrases or sentences to emphasise with vocal variety"],
    "pausePoints": ["3-5 moments where the speaker should pause for effect"],
    "audienceEngagement": ["2-3 techniques to engage the audience during this speech"]
  },
  "stageInstructions": {
    "pausePoints": [
      {"timestamp": "approximate point in speech (e.g., 'after opening')", "instruction": "what to do during this pause"}
    ],
    "emphasisPoints": [
      {"phrase": "the exact phrase to emphasise", "intensity": "light|moderate|strong"}
    ],
    "audienceEngagementMoments": [
      {"moment": "when in the speech", "technique": "specific engagement technique"}
    ]
  },
  "confidenceTips": {
    "deliverySuggestions": ["3-5 practical delivery suggestions"],
    "bodyLanguageTips": ["3-5 body language recommendations"],
    "vocalVariationTips": ["3-5 vocal variety tips"]
  }`;

  // Add special outputs based on speech type
  if (inputs.speechType === 'tedx-speech') {
    userPrompt += `,
  "specialOutputs": {
    "powerfulOpening": "The powerful opening statement or hook",
    "personalStory": "A brief version of the personal story",
    "transformationJourney": "The transformation arc described",
    "lessonLearned": "The key lesson or insight",
    "actionableTakeaway": "The specific action the audience should take",
    "tedxStyleEnding": "The callback closing that circles back to the opening"
  }`;
  } else if (inputs.speechType === 'josh-talks-speech') {
    userPrompt += `,
  "specialOutputs": {
    "relatableOpening": "The relatable opening story or situation",
    "struggle": "The struggle section",
    "challenge": "The challenge faced",
    "breakthrough": "The breakthrough moment",
    "success": "The success achieved",
    "inspiration": "The inspiring message"
  }`;
  } else if (inputs.speechType === 'elevator-pitch') {
    userPrompt += `,
  "specialOutputs": {
    "version30Sec": "The 30-second elevator pitch version",
    "version60Sec": "The 60-second elevator pitch version",
    "version90Sec": "The 90-second elevator pitch version"
  }`;
  } else if (inputs.speechType === 'one-line-speech') {
    userPrompt += `,
  "specialOutputs": {
    "professionalVersion": "Professional one-liner",
    "motivationalVersion": "Motivational one-liner",
    "emotionalVersion": "Emotional one-liner",
    "impactVersion": "Impact one-liner"
  }`;
  } else if (inputs.speechType === 'storytelling-speech') {
    userPrompt += `,
  "specialOutputs": {
    "beginning": "The story beginning - setting the scene",
    "conflict": "The central conflict or challenge",
    "turningPoint": "The decisive turning point",
    "resolution": "How the conflict resolves",
    "lesson": "The universal lesson or insight"
  }`;
  } else {
    userPrompt += `,
  "specialOutputs": {}`;
  }

  // Add anti-repetition constraint if usedStoryHooks are provided
  if (inputs.usedStoryHooks && inputs.usedStoryHooks.length > 0) {
    userPrompt += `\n\nANTI-REPETITION CONSTRAINT: You are an elite executive speechwriter. Here are the 1-line summaries of stories/hooks you have ALREADY used for this user recently:\n${inputs.usedStoryHooks.map((h, i) => `${i + 1}. ${h}`).join('\n')}\n\nCRITICAL RULE: Do NOT use any of the storylines, anecdotes, or scenarios listed above. You must invent a COMPLETELY NEW, highly creative, and unique opening hook and story. Be highly creative — surprise the reader with something fresh.`;
  }

  // Add language reinforcement to the user prompt (redundancy for LLM adherence)
  if (isNonEnglish) {
    userPrompt += `\n\nREMEMBER: Write the ENTIRE speech in ${languageLabel}, NOT in English, NOT in Hindi. All content, notes, and tips must be in ${languageLabel}. Do NOT default to Hindi or English.`;
  }

  userPrompt += `\n\nIMPORTANT: Respond with ONLY valid JSON. No markdown, no code fences, no explanation — just the JSON object.`;

  // Calculate max tokens based on duration — high enough to avoid truncation
  // for complete speech JSON generation (no arbitrary low caps)
  const durationTokens: Record<string, number> = {
    '30s': 16000,
    '1min': 16000,
    '2min': 16000,
    '3min': 24000,
    '5min': 32000,
    '10min': 32000,
    '15min': 48000,
    '20min': 48000,
  };
  const maxTokens = durationTokens[inputs.duration] || 16000;

  return { systemPrompt, userPrompt, maxTokens };
}

export function buildSpeakingEngagementRefinementPrompt(
  originalContent: string,
  refinementType: string,
  inputs: SpeakingEngagementInputs
): { systemPrompt: string; userPrompt: string; maxTokens: number } {
  const refinementMap: Record<string, string> = {
    'improve': 'Improve this speech — make it more impactful, better structured, and more engaging while keeping the original message and tone',
    'shorter': 'Make this speech more concise — remove redundancy, tighten sentences, keep only the most impactful content while preserving the core message',
    'longer': 'Expand this speech — add more depth, stories, examples, and details while maintaining the original structure and tone',
    'professional': 'Make this speech more professional and polished — use more formal language, strengthen arguments, add data points, refine the tone for a corporate audience',
    'inspirational': 'Make this speech more inspirational — add uplifting language, powerful metaphors, emotional stories, and a stronger call to action',
    'emotional': 'Make this speech more emotional — add vulnerability, personal stories, sensory details, and language that touches the heart',
    'humorous': 'Add appropriate humour to this speech — inject wit, clever observations, and light moments while maintaining the core message and not undermining seriousness',
  };

  const instruction = refinementMap[refinementType] || refinementMap['improve'];

  const languageMap: Record<string, string> = {
    'en': 'English', 'hi': 'Hindi', 'mr': 'Marathi', 'es': 'Spanish', 'fr': 'French',
    'de': 'German', 'pt': 'Portuguese', 'it': 'Italian', 'nl': 'Dutch', 'ru': 'Russian',
    'ja': 'Japanese', 'ko': 'Korean', 'zh': 'Chinese (Mandarin)', 'ar': 'Arabic', 'tr': 'Turkish',
    'pl': 'Polish', 'sv': 'Swedish', 'no': 'Norwegian', 'da': 'Danish', 'fi': 'Finnish',
    'cs': 'Czech', 'el': 'Greek', 'he': 'Hebrew', 'th': 'Thai', 'vi': 'Vietnamese',
    'id': 'Indonesian', 'ms': 'Malay', 'fil': 'Filipino', 'bn': 'Bengali', 'ur': 'Urdu',
    'ta': 'Tamil', 'te': 'Telugu', 'kn': 'Kannada', 'ml': 'Malayalam', 'pa': 'Punjabi',
    'gu': 'Gujarati', 'sw': 'Swahili', 'am': 'Amharic',
  };
  const languageLabel = languageMap[inputs.language] || inputs.language || 'English';

  const systemPrompt = `You are an expert speech editor and coach. You refine and improve speeches while maintaining the speaker's authentic voice and the speech's core message. ${instruction}. Write in ${languageLabel}.${languageLabel !== 'English' ? `\n\nCRITICAL OVERRIDE: You MUST write the refined speech ENTIRELY in ${languageLabel}. Do NOT output in English unless English is explicitly requested. This is a strict requirement.` : ''}

OUTPUT FORMAT — CRITICAL: You MUST respond with ONLY a valid JSON object. Do NOT include any thinking, reasoning, chain-of-thought, analysis, or explanatory text before or after the JSON. Do NOT write "Here is the JSON" or "Sure, let me..." — output the JSON object directly starting with { and ending with }. No markdown code fences. No preamble. No commentary.

Respond with ONLY valid JSON containing the refined speech with all the same fields as the original (content, structure, speakerNotes, stageInstructions, confidenceTips, specialOutputs). No markdown, no code fences, no explanation — just the JSON object.`;

  const userPrompt = `Original speech:
${originalContent}

Please ${instruction.toLowerCase()}. Maintain the same JSON structure but with the refined content.`;

  return { systemPrompt, userPrompt, maxTokens: 32000 };
}