/**
 * AI Prompt Library for Intro Script Pipeline
 *
 * Generates intro script data in 2 stages:
 *   Stage 1 — Generate all script variants (type × language × duration × tone combos)
 *   Stage 2 — Refine with brand guardrails if available
 *
 * Uses company context, profile data, and harmony context as seed input.
 */

import { buildHarmonyTextContextBlock, buildHarmonyContext } from './harmonyContextService';

// ============================================
// TYPES
// ============================================

export interface IntroScriptInputs {
  // Company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyCountry?: string;

  // Profile data
  name?: string;
  designation?: string;
  industry?: string;
  experience?: string;
  location?: string;
  achievements?: string;
  education?: string;
  expertise?: string;
  certifications?: string;
  awards?: string;
  mission?: string;
  vision?: string;
  personalStory?: string;
  companyDescriptionOverride?: string;
  companyDescriptionFromProfile?: string;

  // Generation options
  introductionTypes?: string[];
  introductionEntityType?: string;
  eventTypes?: string[];
  languages?: string[];
  durations?: string[];
  tones?: string[];

  // How many script variants to generate
  targetCount: number;

  // Harmony context (loaded externally, passed in)
  harmonyText?: string;
}

export type PartialIntroScriptAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// EVENT TYPE DESCRIPTIONS (for prompt context)
// ============================================

const EVENT_TYPE_DESCRIPTIONS: Record<string, string> = {
  'corporate-meeting': 'A formal internal corporate meeting with leadership, stakeholders, or board members. Professional and results-oriented.',
  'conference': 'A large industry conference or summit with an audience of peers, potential clients, and partners. Authoritative and thought-leading.',
  'webinar': 'An online webinar or virtual presentation where attendees join remotely. Clear, engaging, and webcam-friendly.',
  'workshop': 'An interactive workshop or training session. Hands-on, approachable, and instructional.',
  'product-launch': 'A product launch event or demo day. Exciting, benefit-focused, and milestone-driven.',
  'investor-pitch': 'An investor pitch or funding round presentation. Data-driven, confident, and opportunity-focused.',
  'networking-event': 'A casual networking event or mixer. Warm, memorable, and concise — elevator-pitch style.',
  'award-ceremony': 'An award ceremony or recognition event. Gracious, humble, and celebratory.',
  'employee-onboarding': 'An employee onboarding or team introduction session. Welcoming, inclusive, and culture-building.',
  'annual-function': 'An annual function or company celebration. Inspiring, reflective, and forward-looking.',
  'training-session': 'A training session or workshop for skill development. Educational, structured, and encouraging.',
  'social-media-video': 'A short-form social media video (Instagram Reel, TikTok, LinkedIn video). Punchy, visual, and hook-first.',
  'youtube-video': 'A YouTube video or channel introduction. Personal, authentic, and subscriber-oriented.',
  'podcast': 'A podcast appearance — either hosting or as a guest. Conversational, story-rich, and listener-friendly.',
  'college-seminar': 'A college seminar, guest lecture, or academic presentation. Educational, relatable, and aspirational.',
  'public-event': 'A public event, community gathering, or keynote. Inclusive, visionary, and impactful.',
};

// ============================================
// TONE DESCRIPTIONS
// ============================================

const TONE_DESCRIPTIONS: Record<string, string> = {
  professional: 'Polished, authoritative, and respectful. Uses industry terminology appropriately. Suitable for corporate and formal settings.',
  corporate: 'Formal, structured, and business-focused. Emphasises credentials, track record, and strategic vision.',
  inspirational: 'Uplifting, story-driven, and emotionally engaging. Uses anecdotes and aspirational language to motivate.',
  friendly: 'Warm, approachable, and conversational. Feels like talking to a trusted colleague. Uses inclusive language.',
  motivational: 'Energetic, action-oriented, and empowering. Challenges the audience to think bigger and act now.',
  formal: 'Traditional, ceremonious, and precise. Follows established protocols and respectful address.',
  luxury: 'Sophisticated, exclusive, and refined. Evokes premium quality, heritage, and attention to detail.',
  premium: 'Confident, polished, and value-driven. Highlights unique positioning without being boastful.',
  startup: 'Dynamic, bold, and scrappy. Emphasises innovation, disruption, and rapid growth. Uses modern language.',
  humorous: 'Witty, self-aware, and lighthearted. Uses appropriate humour to connect while remaining credible.',
};

// ============================================
// BANNED PHRASES & ANTI-GENERIC INSTRUCTION
// ============================================

const BANNED_PHRASES = [
  "I'm passionate about",
  "I'm excited to be here",
  "Let me introduce myself",
  "In today's competitive landscape",
  "A little bit about me",
  "I'm honoured to be here",
  "Without further ado",
  "As we all know",
  "At the end of the day",
  "It's a pleasure to be here",
  "I bring to the table",
  "Thinking outside the box",
  "Moving forward",
  "Game-changer",
  "Synergy",
  "Leverage",
  "Empower",
  "Innovative solutions",
  "World-class",
];

const ANTI_GENERIC_INSTRUCTION = `

CRITICAL QUALITY RULES:
- Do NOT use generic placeholder text. Every sentence must be specific to THIS company, person, industry, and event.
- The following phrases are BANNED — do NOT use them: ${BANNED_PHRASES.map(p => `"${p}"`).join(', ')}.
- Opening lines MUST reference the specific event, audience, or context. NOT "Hi, I'm here to introduce..."
- Content MUST include specific details: achievements, metrics, years of experience, industry terms — not vague filler.
- Summary points MUST be concrete, memorable takeaways — not generic statements.
- Each script variant MUST be distinct in structure, emphasis, and tone. Do NOT repeat the same phrases across variants.`;

const JSON_INSTRUCTION = `

CRITICAL OUTPUT FORMAT RULES:
1. Respond with ONLY a single valid JSON object.
2. Do NOT wrap in markdown code fences (no \`\`\`json\`\`\` or \`\`\` blocks).
3. Do NOT include any text, explanation, or commentary before or after the JSON.
4. Do NOT include a "thinking" section or notes — only the JSON object.
5. Ensure all strings are properly escaped. Ensure all arrays and objects are properly closed.
6. If the response is too long, reduce detail per item rather than producing broken JSON.`;

// ============================================
// HELPERS
// ============================================

function buildCompanyAndProfileContext(inputs: IntroScriptInputs): string {
  const parts: string[] = [];

  // Entity type context — personalise the prompt based on who we're introducing
  if (inputs.introductionEntityType) {
    const entityTypeLabels: Record<string, string> = {
      company: 'a company',
      founder: 'a founder',
      employee: 'an employee/team member',
      custom: 'a custom subject',
    };
    parts.push(`Subject Type: Introducing ${entityTypeLabels[inputs.introductionEntityType] || inputs.introductionEntityType}`);
  }

  if (inputs.name) parts.push(`Person/Subject Name: ${inputs.name}`);
  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Company Description: ${inputs.companyDescription}`);
  if (inputs.companyDescriptionOverride) parts.push(`Company Description: ${inputs.companyDescriptionOverride}`);
  if (inputs.companyIndustry) parts.push(`Industry: ${inputs.companyIndustry}`);
  if (inputs.companyCountry) parts.push(`Country: ${inputs.companyCountry}`);
  if (inputs.designation) parts.push(`Designation/Title: ${inputs.designation}`);
  if (inputs.industry) parts.push(`Profile Industry: ${inputs.industry}`);
  if (inputs.experience) parts.push(`Experience: ${inputs.experience}`);
  if (inputs.location) parts.push(`Location: ${inputs.location}`);
  if (inputs.achievements) parts.push(`Key Achievements: ${inputs.achievements}`);
  if (inputs.education) parts.push(`Education: ${inputs.education}`);
  if (inputs.expertise) parts.push(`Expertise: ${inputs.expertise}`);
  if (inputs.certifications) parts.push(`Certifications: ${inputs.certifications}`);
  if (inputs.awards) parts.push(`Awards & Recognition: ${inputs.awards}`);
  if (inputs.mission) parts.push(`Mission: ${inputs.mission}`);
  if (inputs.vision) parts.push(`Vision: ${inputs.vision}`);
  if (inputs.personalStory) parts.push(`Personal Story: ${inputs.personalStory}`);
  if (inputs.companyDescriptionFromProfile) parts.push(`Company (from profile): ${inputs.companyDescriptionFromProfile}`);

  if (inputs.harmonyText) {
    parts.push(`\nBrand & Harmony Context:\n${inputs.harmonyText}`);
  }

  return parts.join('\n');
}

function buildEventTypeGuidance(eventTypes: string[]): string {
  return eventTypes
    .map((et) => `- ${et}: ${EVENT_TYPE_DESCRIPTIONS[et] || 'A ' + et.replace(/-/g, ' ') + ' event.'}`)
    .join('\n');
}

function buildToneGuidance(tones: string[]): string {
  return tones
    .map((t) => `- ${t}: ${TONE_DESCRIPTIONS[t] || 'A ' + t + ' tone.'}`)
    .join('\n');
}

// ============================================
// STAGE 1: GENERATE ALL SCRIPT VARIANTS
// ============================================

export function buildIntroScriptPrompt(inputs: IntroScriptInputs): PromptResult {
  const count = Math.min(inputs.targetCount || 10, 10);
  const introductionTypes = inputs.introductionTypes?.length ? inputs.introductionTypes : [];
  const eventTypes = inputs.eventTypes?.length ? inputs.eventTypes : ['corporate-meeting', 'conference', 'webinar', 'networking-event', 'social-media-video'];
  const languages = inputs.languages?.length ? inputs.languages : ['en'];
  const tones = inputs.tones?.length ? inputs.tones : ['professional', 'friendly', 'inspirational'];
  const durations = inputs.durations?.length ? inputs.durations : ['1min', '2min'];

  const eventTypeGuidance = buildEventTypeGuidance(eventTypes);
  const toneGuidance = buildToneGuidance(tones);

  // Build introduction type constraints
  let introTypeConstraint = '';
  if (introductionTypes.length > 0) {
    introTypeConstraint = `\n\nINTRODUCTION TYPE FOCUS:\nThe scripts MUST use ONLY these introduction types: ${introductionTypes.join(', ')}.\nGenerate scripts focused on introducing ${introductionTypes.map(t => {
      const labels: Record<string, string> = { company: 'a company/organisation', founder: 'a founder/CEO', employee: 'an employee/team member', team: 'a team/department', speaker: 'a speaker/presenter', guest: 'a guest/invitee', 'event-host': 'an event host/MC' };
      return labels[t] || t;
    }).join(' or ')}.`;
  }

  // Build language constraint
  let languageConstraint = '';
  if (languages.length > 0 && !(languages.length === 1 && languages[0] === 'en')) {
    languageConstraint = `\n\nLANGUAGE REQUIREMENTS:\nGenerate scripts in these languages: ${languages.map(l => {
      const labels: Record<string, string> = { en: 'English', hi: 'Hindi', mr: 'Marathi', bilingual: 'Bilingual (Hindi-English)', multilingual: 'Multilingual' };
      return labels[l] || l;
    }).join(', ')}.\nFor Hindi/Marathi scripts: write the script entirely in that language using its native script (Devanagari for Hindi/Marathi).\nFor bilingual scripts: interleave English and Hindi naturally as a bilingual speaker would.\nFor multilingual scripts: provide a primary version with natural language switching.`;
  }

  // Build duration constraint
  let durationConstraint = '';
  if (durations.length > 0) {
    durationConstraint = `\n\nDURATION FOCUS:\nGenerate scripts primarily in these durations: ${durations.join(', ')}.\nWord count targets: 30s = 50-70 words, 1min = 100-140 words, 2min = 200-260 words, 3min = 300-380 words, 5min = 500-600 words.`;
  }

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are an expert introduction script writer and speech coach. Generate ${count} diverse intro script variants for the given company and/or person. Each variant should be tailored to a different event type, tone, and context, creating a comprehensive library of ready-to-use introduction scripts.
${introTypeConstraint}${languageConstraint}${durationConstraint}
EVENT TYPE GUIDANCE:
${eventTypeGuidance}

TONE GUIDANCE:
${toneGuidance}

DIVERSITY REQUIREMENTS:
- Each script MUST have a different combination of introductionType + eventType + tone.
- Content MUST be completely distinct across scripts — no reusing phrases or structural patterns.
- Summary points MUST be unique per script, reflecting the specific context and audience.
- Adapt language, structure, and emphasis based on the event type and tone specified.
- Use the person's REAL name, title, achievements, and company details provided in the context. NEVER use placeholder names like "John Doe".
- Scripts for Hindi/Marathi must be written entirely in the target language — NOT transliterated English.
${ANTI_GENERIC_INSTRUCTION}${JSON_INSTRUCTION}

Your response must match this EXACT JSON schema:
{
  "scripts": [
    {
      "name": "string — descriptive script name using the person/company's real name, e.g. 'Rajesh Sharma — Tech Conference Keynote'",
      "introductionType": "string — one of: company, founder, employee, team, speaker, guest, event-host",
      "eventType": "string — one of: corporate-meeting, conference, webinar, workshop, product-launch, investor-pitch, networking-event, award-ceremony, employee-onboarding, annual-function, training-session, social-media-video, youtube-video, podcast, college-seminar, public-event",
      "language": "string — one of: en, hi, mr, bilingual, multilingual",
      "duration": "string — one of: 30s, 1min, 2min, 3min, 5min",
      "tone": "string — one of: professional, corporate, inspirational, friendly, motivational, formal, luxury, premium, startup, humorous",
      "context": "string — one of: stage, self, video, networking, investor, conference-speaker, award-ceremony",
      "content": "string — the complete introduction script text, fully written out, specific to the event and tone. NOT a template with blanks — a ready-to-deliver script.",
      "summaryPoints": ["array of 3-6 memorable key points or takeaways from the introduction"],
      "personalizationNotes": "string — notes on how to customise this script for different audiences or situations, 1-3 sentences",
      "designation": "string — the role/title being introduced (if applicable)",
      "industry": "string — the industry context",
      "experience": "string — relevant experience highlight",
      "mission": "string — the mission or purpose statement",
      "vision": "string — the vision or forward-looking statement",
      "status": "string — one of: draft, review. Assign 'review' if the script is complete and ready for human review. Assign 'draft' if it needs editing."
    }
  ]
}

Generate exactly ${count} scripts. Ensure variety across event types and tones.`;

  const userPrompt = `Generate ${count} intro script variants for:\n\n${buildCompanyAndProfileContext(inputs)}\n\nTarget introduction types: ${introductionTypes.length ? introductionTypes.join(', ') : 'all types'}\nTarget event types: ${eventTypes.join(', ')}\nTarget tones: ${tones.join(', ')}\nTarget languages: ${languages.join(', ')}\nTarget durations: ${durations.join(', ')}`;

  return { systemPrompt, userPrompt, maxTokens: 6000 };
}

// ============================================
// STAGE 2: REFINE WITH BRAND GUARDRAILS
// ============================================

export function buildIntroScriptRefinementPrompt(
  inputs: IntroScriptInputs,
  scripts: PartialIntroScriptAnalysis[]
): PromptResult {
  const scriptSummaries = scripts.map((s, i) => {
    const parts = [`Script ${i + 1}:`];
    if (s.name) parts.push(`  Name: ${s.name}`);
    if (s.introductionType) parts.push(`  Type: ${s.introductionType}`);
    if (s.eventType) parts.push(`  Event: ${s.eventType}`);
    if (s.tone) parts.push(`  Tone: ${s.tone}`);
    if (s.duration) parts.push(`  Duration: ${s.duration}`);
    if (s.context) parts.push(`  Context: ${s.context}`);
    if (s.content) parts.push(`  Content (first 200 chars): ${String(s.content).substring(0, 200)}...`);
    return parts.join('\n');
  }).join('\n\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a brand voice and introduction script editor. Refine the following ${scripts.length} intro scripts to ensure they align with the company's brand voice, tone, and positioning. Make the scripts more impactful, memorable, and brand-consistent while preserving the original intent and structure.

IMPROVEMENT CRITERIA:
- Ensure each script's tone matches the specified tone parameter EXACTLY.
- Replace any generic language with specific, brand-relevant content.
- Strengthen opening hooks — they must grab attention within the first 5 seconds.
- Ensure summary points are concrete and memorable.
- Verify personalization notes offer genuinely useful customisation advice.
- Check that script length is appropriate for the specified duration.
- Scripts for '30s' should be concise (50-70 words), '1min' should be 100-140 words, '2min' should be 200-260 words, '3min' should be 300-380 words, '5min' should be 500-600 words.
${ANTI_GENERIC_INSTRUCTION}${JSON_INSTRUCTION}

Your response must match this EXACT JSON schema:
{
  "scripts": [
    {
      "name": "string",
      "introductionType": "string",
      "eventType": "string",
      "language": "string",
      "duration": "string",
      "tone": "string",
      "context": "string",
      "content": "string — the refined, brand-aligned introduction script",
      "summaryPoints": ["array of 3-6 refined key points"],
      "personalizationNotes": "string — refined customisation notes",
      "designation": "string",
      "industry": "string",
      "experience": "string",
      "mission": "string",
      "vision": "string",
      "status": "string"
    }
  ]
}

Return the same number of scripts (${scripts.length}) in the same order, with refinements applied.`;

  const userPrompt = `Refine these intro scripts for brand alignment:\n\n${scriptSummaries}\n\n${buildCompanyAndProfileContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 5000 };
}