/**
 * AI Prompt Library for Video Content Pipeline
 *
 * Generates video content data in 3 stages using company context, ICP data,
 * product info, and brand strategy. Follows the multi-item pattern to generate
 * 6 diverse video content pieces.
 */

// ============================================
// TYPES
// ============================================

export interface VideoContentPipelineInputs {
  /**
   * The user's own brief from the "Generate with AI" popup or the AI Chat
   * generation flow — audience, topics, tone, goals and the chosen data
   * sources. Stated as the highest-priority instruction in the prompt.
   */
  customInstructions?: string;

  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  productNames?: string[];
  productDescriptions?: string[];

  // User-provided inputs
  topic?: string;
  url?: string;

  targetCount: number;
}

export type PartialVideoContentAnalysis = Record<string, any>;

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// DIVERSITY HINTS
// ============================================

const DIVERSITY_HINTS = [
  'Product demo video — showcase a key product feature or walkthrough for prospects or new customers',
];

// ============================================
// HELPERS
// ============================================

function buildCompanyContext(inputs: VideoContentPipelineInputs): string {
  const parts: string[] = [];
  // The user's brief goes FIRST and is marked authoritative — it is the one
  // part of the context they typed themselves, so it must win over the derived
  // company/ICP/brand material below when the two disagree.
  if (inputs.customInstructions?.trim()) {
    parts.push(
      `USER BRIEF (highest priority — follow this over the general company context below):\n${inputs.customInstructions.trim()}\n`
    );
  }
  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Description: ${inputs.companyDescription}`);
  if (inputs.companyIndustry) parts.push(`Industry: ${inputs.companyIndustry}`);
  if (inputs.companyBusinessModel) parts.push(`Business Model: ${inputs.companyBusinessModel}`);
  if (inputs.companyTargetAudience) parts.push(`Target Audience: ${inputs.companyTargetAudience}`);
  if (inputs.companyPrimaryOffering) parts.push(`Primary Offering: ${inputs.companyPrimaryOffering}`);
  if (inputs.companyUsps?.length) parts.push(`Key USPs: ${inputs.companyUsps.join(', ')}`);
  if (inputs.topic) parts.push(`\nTopic Focus: ${inputs.topic}`);
  if (inputs.url) parts.push(`Reference URL: ${inputs.url}`);

  if (inputs.icpName) {
    const icpParts: string[] = [];
    icpParts.push(`Ideal Customer: ${inputs.icpName}`);
    if (inputs.icpIndustry) icpParts.push(`Industry: ${inputs.icpIndustry}`);
    if (inputs.icpCompanySize) icpParts.push(`Size: ${inputs.icpCompanySize}`);
    if (inputs.icpPainPoints?.length) icpParts.push(`Pain Points: ${inputs.icpPainPoints.join(', ')}`);
    if (inputs.icpBusinessGoals?.length) icpParts.push(`Goals: ${inputs.icpBusinessGoals.join(', ')}`);
    parts.push(`\nICP Context:\n${icpParts.join('\n')}`);
  }

  if (inputs.brandArchetype || inputs.brandPositioning) {
    const brandParts: string[] = [];
    if (inputs.brandArchetype) brandParts.push(`Brand Archetype: ${inputs.brandArchetype}`);
    if (inputs.brandPersonality?.length) brandParts.push(`Brand Personality: ${inputs.brandPersonality.join(', ')}`);
    if (inputs.brandValues?.length) brandParts.push(`Brand Values: ${inputs.brandValues.join(', ')}`);
    if (inputs.brandPositioning) brandParts.push(`Brand Positioning: ${inputs.brandPositioning}`);
    if (inputs.brandVoice) brandParts.push(`Brand Voice: ${inputs.brandVoice}`);
    parts.push(`\nBrand Strategy:\n${brandParts.join('\n')}`);
  }

  if (inputs.productNames?.length) {
    const productParts: string[] = [];
    inputs.productNames.forEach((name, i) => {
      const desc = inputs.productDescriptions?.[i];
      productParts.push(desc ? `${name}: ${desc}` : name);
    });
    parts.push(`\nProducts:\n${productParts.join('\n')}`);
  }

  return parts.join('\n');
}

const JSON_INSTRUCTION = '\n\nCRITICAL OUTPUT FORMAT RULES:\n1. Respond with ONLY a single valid JSON object.\n2. Do NOT wrap in markdown code fences (no ```json``` or ``` blocks).\n3. Do NOT include any text, explanation, or commentary before or after the JSON.\n4. Ensure all strings are properly escaped. Ensure all arrays and objects are properly closed.\n5. If the response is too long, reduce detail per item rather than producing broken JSON.';

// ============================================
// STAGE 1: VIDEO IDENTITY & STRATEGY
// ============================================

export function buildVideoContentIdentityPrompt(inputs: VideoContentPipelineInputs): PromptResult {
  const count = Math.min(inputs.targetCount, 6);
  const hints = DIVERSITY_HINTS.slice(0, count);
  const diversityLines = hints.map((h, i) => `Video ${i + 1}: ${h}`).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B video content strategist AI. Generate ${count} video content piece${count > 1 ? 's' : ''} for the given company, based on the provided topic and reference URL.${count > 1 ? ' Each video should target a different type, category, and audience.' : ''}

${count > 1 ? `DIVERSITY GUIDELINES — follow these to ensure variety:\n${diversityLines}\n\nEach video must have a distinct type, category, source, and access level.` : ''}${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "videos": [
    {
      "name": "string — descriptive video title, e.g. 'CloudDial Product Walkthrough for Sales Teams'",
      "description": "string — 1-2 sentence summary of what this video covers and who it is for",
      "type": "string — one of: educational, product-demo, service-walkthrough, sop-video, company-policy, hr-training, technical-tutorial, sales-training, founder-message, customer-onboarding, webinar-recording, team-training, interview, feature-update, marketing-strategy, internal-communication, compliance-training, support-tutorial",
      "category": "string — one of: product-training, service-training, educational, company-policies, hr-training, sop-videos, sales-training, technical-tutorials, customer-support, founder-sessions, team-onboarding, compliance, marketing-training, crm-training, software-tutorials, internal-meetings, webinar-recordings, client-training, knowledge-sharing",
      "source": "string — one of: youtube, vimeo, loom, google-drive, dropbox, wistia, internal-cdn, other",
      "accessLevel": "string — one of: public, team, department, manager-only, hr-only",
      "department": "string — e.g. 'Sales', 'Marketing', 'Engineering', 'Customer Success'",
      "language": "string — e.g. 'en'",
      "tags": ["array of 3-5 relevant tags"],
      "targetAudience": "string — who should watch this video, e.g. 'Sales Directors at mid-market SaaS companies'"
    }
  ]
}

Generate exactly ${count} video${count > 1 ? 's' : ''}.${count > 1 ? ' The array order must match the diversity guidelines above.' : ''}`;

  const userPrompt = `Generate ${count} diverse video content pieces for:\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 4000 };
}

// ============================================
// STAGE 2: VIDEO CONTENT & STRUCTURE
// ============================================

export function buildVideoContentContentPrompt(inputs: VideoContentPipelineInputs, partials: PartialVideoContentAnalysis[]): PromptResult {
  const identitySummaries = partials.map((p, i) => {
    const parts = [`Video ${i + 1}:`];
    if (p.name) parts.push(`  Title: ${p.name}`);
    if (p.type) parts.push(`  Type: ${p.type}`);
    if (p.category) parts.push(`  Category: ${p.category}`);
    if (p.targetAudience) parts.push(`  Audience: ${p.targetAudience}`);
    return parts.join('\n');
  }).join('\n\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a professional B2B video content producer AI. For each of the ${partials.length} videos, generate a detailed content outline, full production-ready script, key notes, and shot list.

IMPORTANT: The "script" field MUST be a detailed, production-ready video script suitable for AI video generation. It must include ALL of the following sections, each clearly labeled:

1. **Introduction / Hook** — Open with a compelling hook that grabs attention in the first 5 seconds. Set the context and promise what the viewer will learn or gain.

2. **Scene-by-Scene Narration** — For each major section of the video, provide:
   - Visual description (what appears on screen)
   - Voiceover / narration text (what the narrator says)
   - On-screen text overlays or graphics descriptions
   - Transition between scenes (e.g., "Fade to...", "Cut to...", "Dissolve into...")

3. **Talking Points** — 3-5 key messages or data points that must be communicated, each with a brief explanation of how to present them visually and verbally.

4. **Call-to-Action** — A clear, specific CTA directing the viewer what to do next (sign up, request demo, download resource, etc.), with visual framing instructions.

5. **Closing** — A concise wrap-up that reinforces the main takeaway, includes a brief sign-off, and ends with the brand logo/title card description.

The script should be detailed enough that an AI video generator can create a complete video from it. Do NOT write just a short paragraph — write a full, structured script with scene descriptions and narration.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "videos": [
    {
      "name": "string — same title from stage 1",
      "description": "string — expanded description, 2-3 sentences",
      "summary": "string — brief video summary for the viewer, 2-3 sentences",
      "keyNotes": ["array of 4-6 key takeaways or notes from this video"],
      "script": "string — FULL production-ready video script with: Introduction/Hook, Scene-by-Scene Narration (with visual descriptions, voiceover text, transitions), Talking Points, Call-to-Action, and Closing. Must be detailed and comprehensive, not a brief outline.",
      "shotList": ["array of 5-8 shot descriptions, e.g. 'Wide shot of team collaborating in modern office', 'Close-up of dashboard analytics with data highlights'"],
      "sections": [
        {
          "title": "string — section title",
          "content": "string — detailed content outline for this section, 2-4 sentences",
          "order": "number — display order starting from 0"
        }
      ],
      "duration": "string — estimated duration, e.g. '3:45'",
      "timestampNotes": [
        {
          "time": "string — timestamp e.g. '0:45'",
          "note": "string — what happens at this timestamp"
        }
      ]
    }
  ]
}

Generate exactly ${partials.length} videos. Include 4-6 sections per video and 5-8 timestamp notes. The script MUST be detailed and production-ready — do NOT generate only a brief outline.`;

  const userPrompt = `Generate full content for these video pieces:\n\n${identitySummaries}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 8000 };
}

// ============================================
// STAGE 3: TRAINING & USAGE GUIDANCE
// ============================================

export function buildVideoContentTrainingPrompt(inputs: VideoContentPipelineInputs, partials: PartialVideoContentAnalysis[]): PromptResult {
  const identitySummaries = partials.map((p, i) => {
    const parts = [`Video ${i + 1}:`];
    if (p.name) parts.push(`  ${p.name}`);
    if (p.type) parts.push(`  Type: ${p.type}`);
    return parts.join(' ');
  }).join('\n');

  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B video enablement AI. For each of the ${partials.length} videos, generate usage guidance, best practices, and effectiveness tips.${JSON_INSTRUCTION}

Your response must match this exact JSON schema:
{
  "videos": [
    {
      "usageNotes": "string — 2-3 sentences about when and how to use this video effectively",
      "bestPractices": ["array of 3-5 best practices for creating and distributing this type of video"],
      "effectivenessTips": ["array of 2-3 tips for maximizing viewer engagement and retention"],
      "pdfReferences": ["array of 2-3 related documents or resources that complement this video"],
      "downloadableResources": ["array of 2-3 downloadable resources to pair with this video, e.g. 'Quick Start Guide PDF'"]
    }
  ]
}

Generate exactly ${partials.length} videos. The array order must match the identity order.`;

  const userPrompt = `Generate usage guidance for these video content pieces:\n\n${identitySummaries}\n\n${buildCompanyContext(inputs)}`;

  return { systemPrompt, userPrompt, maxTokens: 3000 };
}

// ============================================
// ENHANCEMENT PROMPT
// ============================================

export function buildVideoContentEnhancementPrompt(
  stageName: string,
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `RESPOND WITH ONLY VALID JSON. No markdown, no explanation, no code fences.

You are a B2B video content strategist AI performing a refinement pass. The previous analysis for "${stageName}" had low confidence on certain fields. Provide more specific, detailed content for the indicated fields.${JSON_INSTRUCTION}

Respond with the SAME JSON schema as before, but with improved values for the flagged fields. Keep the fields that already had good results unchanged.`;

  const userPrompt = `Previous analysis:\n${JSON.stringify(stageOutput, null, 2)}\n\nFields needing improvement (low confidence): ${lowConfidenceFields.join(', ')}\n\nPlease refine the analysis.`;

  return { systemPrompt, userPrompt, maxTokens: 2000 };
}

// ============================================
// VIDEO PROMPT BUILDER (for AI video generation)
// ============================================

export interface VideoPromptInput {
  description?: string;
  script?: string;
  summary?: string;
  keyNotes?: string[];
  tags?: string[];
  language?: string;
  department?: string;
  targetAudience?: string;
  videoType?: string;
  companyName?: string;
}

/**
 * Build an optimized video generation prompt from the reviewed content fields.
 * This produces a cinematic, visual prompt suitable for AI video generators like Luma.
 */
export function buildVideoGenerationPrompt(input: VideoPromptInput): string {
  const parts: string[] = [];

  // Core visual description
  if (input.description) {
    parts.push(`A professional video about: ${input.description.trim()}`);
  }

  // Script-based scene descriptions
  if (input.script) {
    // Extract key scenes from the script for visual guidance
    const scriptExcerpt = input.script.length > 800 ? input.script.slice(0, 800) + '...' : input.script;
    parts.push(`Key scenes and narration: ${scriptExcerpt}`);
  }

  // Summary as overall tone
  if (input.summary) {
    parts.push(`Overall tone and message: ${input.summary.trim()}`);
  }

  // Key notes as visual highlights
  if (input.keyNotes && input.keyNotes.length > 0) {
    parts.push(`Key visual highlights: ${input.keyNotes.join('; ')}`);
  }

  // Tags for style guidance
  if (input.tags && input.tags.length > 0) {
    parts.push(`Style tags: ${input.tags.join(', ')}`);
  }

  // Audience and department context
  if (input.targetAudience) {
    parts.push(`Target audience: ${input.targetAudience}`);
  }
  if (input.department) {
    parts.push(`Department context: ${input.department}`);
  }

  // Video type guidance
  if (input.videoType) {
    const typeGuidance: Record<string, string> = {
      'educational': 'Clear, instructional visuals with text overlays and step-by-step demonstrations',
      'product-demo': 'Product showcase with close-ups, feature highlights, and user interaction sequences',
      'service-walkthrough': 'Professional service demonstration with process flow visuals',
      'sop-video': 'Standard operating procedure walkthrough with clear process steps',
      'company-policy': 'Corporate policy explainer with professional graphics and text callouts',
      'hr-training': 'Employee training material with engaging, friendly visuals',
      'technical-tutorial': 'Technical demonstration with screen recordings and code/technical visuals',
      'sales-training': 'Sales methodology training with scenario-based visuals and technique demonstrations',
      'founder-message': 'Executive message with professional talking head and brand visuals',
      'customer-onboarding': 'Welcome and orientation video with friendly, guided visuals',
      'marketing-strategy': 'Strategic marketing visualization with data-driven graphics and campaign visuals',
      'internal-communication': 'Internal announcement with professional, clean graphics',
    };
    const guidance = typeGuidance[input.videoType];
    if (guidance) {
      parts.push(`Video format guidance: ${guidance}`);
    }
  }

  // Language guidance
  if (input.language && input.language !== 'en') {
    parts.push(`Language/cultural context: ${input.language}`);
  }

  // Company branding
  if (input.companyName) {
    parts.push(`Company/brand: ${input.companyName}`);
  }

  // Quality and production standards
  parts.push('Production quality: cinematic, professional, high-resolution, smooth transitions, polished corporate style');

  return parts.join('. ') + '.';
}