/**
 * AI Prompt Library for Audio Content Pipeline
 *
 * 3-step generation workflow:
 * Step 1: Generate lyrics/content (song concept, full lyrics, chorus, verses, bridge, genre, mood, tags)
 * Step 2: Generate optimized Suno prompt from edited lyrics + context
 * Step 3: Suno audio generation (handled by sunoService, not prompts)
 *
 * Plus enhancement prompt for low-confidence field retry.
 */

// ============================================
// TYPES
// ============================================

export interface AudioContentPipelineInputs {
  customInstructions?: string;

  // Company context
  companyName: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // ICP context
  icpName?: string;
  icpIndustry?: string;
  icpCompanySize?: string;
  icpPainPoints?: string[];
  icpBusinessGoals?: string[];

  // Brand context
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // Product context
  productNames?: string[];
  productDescriptions?: string[];

  // User form inputs (Step 1)
  songTitle: string;
  topic?: string;
  description?: string;
  prompt?: string;
  genre?: string;
  mood?: string;
  language?: string;
  singerType?: string;
  duration?: string;
  instrumentStyle?: string;
  negativePrompt?: string;
  targetAudience?: string;
}

export interface AudioContentPromptInputs {
  // The edited lyrics from a previous step (optional — may not be available yet)
  lyrics?: string;

  // Song context
  songTitle?: string;
  topic?: string;
  prompt?: string;
  genre?: string;
  mood?: string;
  language?: string;
  singerType?: string;
  duration?: string;
  instrumentStyle?: string;
  negativePrompt?: string;

  // Generated content from Step 1 (enriches the prompt)
  songConcept?: string;
  chorus?: string;
  verses?: string[];
  bridge?: string;

  // Company context (for brand-aligned prompts)
  companyName?: string;
  companyDescription?: string;
  companyIndustry?: string;
  companyBusinessModel?: string;
  companyTargetAudience?: string;
  companyPrimaryOffering?: string;
  companyUsps?: string[];

  // Brand context
  brandArchetype?: string;
  brandPersonality?: string[];
  brandValues?: string[];
  brandPositioning?: string;
  brandVoice?: string;

  // Product context
  productNames?: string[];
  productDescriptions?: string[];
}

export interface PromptResult {
  systemPrompt: string;
  userPrompt: string;
  maxTokens: number;
}

// ============================================
// CONTEXT BUILDER (shared)
// ============================================

function buildCompanyContext(inputs: AudioContentPipelineInputs | AudioContentPromptInputs): string {
  const parts: string[] = [];

  if (inputs.companyName) parts.push(`Company: ${inputs.companyName}`);
  if (inputs.companyDescription) parts.push(`Company 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(`USPs: ${inputs.companyUsps.join(', ')}`);

  if ('icpName' in inputs && (inputs.icpName || inputs.icpIndustry)) {
    parts.push('\nICP Context:');
    if (inputs.icpName) parts.push(`  ICP Name: ${inputs.icpName}`);
    if (inputs.icpIndustry) parts.push(`  ICP Industry: ${inputs.icpIndustry}`);
    if (inputs.icpCompanySize) parts.push(`  ICP Company Size: ${inputs.icpCompanySize}`);
    if (inputs.icpPainPoints?.length) parts.push(`  ICP Pain Points: ${inputs.icpPainPoints.join(', ')}`);
    if (inputs.icpBusinessGoals?.length) parts.push(`  ICP Business Goals: ${inputs.icpBusinessGoals.join(', ')}`);
  }

  if (inputs.brandArchetype || inputs.brandVoice) {
    parts.push('\nBrand Context:');
    if (inputs.brandArchetype) parts.push(`  Brand Archetype: ${inputs.brandArchetype}`);
    if (inputs.brandPersonality?.length) parts.push(`  Brand Personality: ${inputs.brandPersonality.join(', ')}`);
    if (inputs.brandValues?.length) parts.push(`  Brand Values: ${inputs.brandValues.join(', ')}`);
    if (inputs.brandPositioning) parts.push(`  Brand Positioning: ${inputs.brandPositioning}`);
    if (inputs.brandVoice) parts.push(`  Brand Voice: ${inputs.brandVoice}`);
  }

  if (inputs.productNames?.length) {
    parts.push('\nProduct Context:');
    inputs.productNames.forEach((name, i) => {
      const desc = inputs.productDescriptions?.[i];
      parts.push(`  - ${name}${desc ? `: ${desc}` : ''}`);
    });
  }

  return parts.join('\n');
}

// ============================================
// STEP 1: LYRICS/CONTENT GENERATION PROMPT
// ============================================

export function buildAudioContentLyricsPrompt(inputs: AudioContentPipelineInputs): PromptResult {
  const companyContext = buildCompanyContext(inputs);

  const systemPrompt = `You are an expert music producer and songwriter AI assistant. You create compelling, professional-quality song content including concept, lyrics, genre analysis, mood selection, and music tags.

Your output MUST be valid JSON with this exact structure:
{
  "songTitle": "string - The refined/enhanced song title",
  "songConcept": "string - A brief concept summary (1-2 sentences describing the song's theme, narrative, and emotional arc)",
  "lyrics": "string - Complete song lyrics with sections clearly marked using [Verse 1], [Chorus], [Verse 2], [Bridge], [Outro] tags",
  "chorus": "string - Just the chorus lyrics (the hook section)",
  "verses": ["string - Verse 1 lyrics", "string - Verse 2 lyrics (if applicable)"],
  "bridge": "string - Bridge section lyrics (if applicable, or empty string)",
  "genreSuggestions": ["string - 3-5 genre suggestions that best fit the song"],
  "mood": "string - The primary mood/emotion of the song",
  "musicTags": ["string - 5-10 descriptive tags for music categorization"]
}

Rules for lyrics:
- Structure with [Verse 1], [Chorus], [Verse 2], [Bridge], [Outro] tags
- Keep lyrics concise (2-4 verses, 1-2 choruses)
- Make lyrics emotionally resonant and memorable
- Ensure natural rhythm and rhyme scheme
- Include a strong hook in the chorus
- The "chorus" field should contain ONLY the chorus text (no tags)
- The "verses" array should contain ONLY the verse text (no tags)
- The "bridge" field should contain ONLY the bridge text (no tags, or empty string if no bridge)
- The "lyrics" field should contain the COMPLETE formatted lyrics WITH section tags`;

  const userParts: string[] = [];
  userParts.push(`## Song Requirements`);
  userParts.push(`- **Song Title**: ${inputs.songTitle}`);
  if (inputs.topic) userParts.push(`- **Topic**: ${inputs.topic}`);
  if (inputs.description) userParts.push(`- **Description**: ${inputs.description}`);
  if (inputs.prompt) userParts.push(`- **Concept/Prompt**: ${inputs.prompt}`);
  if (inputs.genre) userParts.push(`- **Genre**: ${inputs.genre}`);
  if (inputs.mood) userParts.push(`- **Mood**: ${inputs.mood}`);
  if (inputs.language) userParts.push(`- **Language**: ${inputs.language}`);
  if (inputs.singerType) userParts.push(`- **Singer Type**: ${inputs.singerType}`);
  if (inputs.duration) userParts.push(`- **Target Duration**: ${inputs.duration} seconds`);
  if (inputs.instrumentStyle) userParts.push(`- **Instrument Style**: ${inputs.instrumentStyle}`);
  if (inputs.negativePrompt) userParts.push(`- **What to Avoid**: ${inputs.negativePrompt}`);
  if (inputs.targetAudience) userParts.push(`- **Target Audience**: ${inputs.targetAudience}`);

  if (companyContext) {
    userParts.push(`\n## Company & Brand Context\n${companyContext}`);
  }

  if (inputs.customInstructions) {
    userParts.push(`\n## Additional Instructions\n${inputs.customInstructions}`);
  }

  userParts.push(`\nGenerate the song concept, complete lyrics, chorus, verses, bridge, genre suggestions, mood, and music tags. Return ONLY valid JSON.`);

  const userPrompt = userParts.join('\n');

  return {
    systemPrompt,
    userPrompt,
    maxTokens: 4000,
  };
}

// Keep backward compatibility alias
export const buildAudioContentPrompt = buildAudioContentLyricsPrompt;

// ============================================
// STEP 2: SUNO PROMPT GENERATION PROMPT
// ============================================

export function buildAudioContentPromptGenerationPrompt(inputs: AudioContentPromptInputs): PromptResult {
  const companyContext = buildCompanyContext(inputs);

  const systemPrompt = `You are an expert at creating detailed, structured prompts for Suno AI music generation. You take song lyrics, genre, mood, and other musical context and produce a comprehensive, well-organized prompt that will generate the best possible audio output from Suno.

Your output MUST be valid JSON with this exact structure:
{
  "optimizedSunoPrompt": "string - A detailed, multi-line prompt for Suno AI music generation. This must be a comprehensive prompt that includes ALL of the following sections, each on a new line, formatted as a clear structured prompt:",
  "suggestedTags": ["string - 8-12 specific tags for the Suno generation (genre, mood, instruments, tempo, vocal style, energy descriptors)"],
  "confidence": "number - Your confidence in this prompt (0.0-1.0)"
}

The optimizedSunoPrompt MUST include ALL of these sections, each on its own line:
1. Genre and style (e.g., "Genre: Indie Hindi Pop with electronic influences")
2. Mood and emotional tone (e.g., "Mood: Nostalgic, uplifting with bittersweet undertones")
3. Tempo and energy (e.g., "Tempo: Mid-tempo, 110-120 BPM, driving rhythm")
4. Vocal style (e.g., "Vocals: Soulful male vocals with expressive delivery, soft verses and powerful chorus")
5. Instrumentation (e.g., "Instruments: Acoustic guitar, subtle synth pads, gentle percussion, bass")
6. Production notes (e.g., "Production: Warm analog feel, reverb on vocals, layered harmonies in chorus")
7. Key musical qualities and influences (e.g., "Style notes: Blend of A.R. Rahman melodicism with modern indie production")
8. Any specific requirements from the user's input (language, duration, what to avoid, etc.)

Rules:
- Be specific and descriptive — do NOT summarize into a single line
- Include tempo or energy descriptors (e.g., "upbeat", "slow", "driving", "ethereal")
- Specify vocal characteristics if applicable (e.g., "powerful male vocals", "soft female vocals with breathy tone")
- If the song is instrumental, mention that explicitly and describe the instrumental arrangement in detail
- Incorporate the emotional tone from the lyrics into the prompt
- Reference the song concept, chorus, and lyrical themes when available
- If the user provided a concept/prompt, incorporate their specific instructions
- Each section should be detailed enough for Suno to generate a distinct, high-quality song
- Do NOT use abbreviations — write out full descriptions`;

  const userParts: string[] = [];
  if (inputs.lyrics) {
    userParts.push(`## Song Lyrics\n${inputs.lyrics}`);
  }
  userParts.push(`\n## Song Context`);
  if (inputs.songTitle) userParts.push(`- **Song Title**: ${inputs.songTitle}`);
  if (inputs.topic) userParts.push(`- **Topic**: ${inputs.topic}`);
  if (inputs.prompt) userParts.push(`- **User Concept/Prompt**: ${inputs.prompt}`);
  if (inputs.genre) userParts.push(`- **Genre**: ${inputs.genre}`);
  if (inputs.mood) userParts.push(`- **Mood**: ${inputs.mood}`);
  if (inputs.language) userParts.push(`- **Language**: ${inputs.language}`);
  if (inputs.singerType) userParts.push(`- **Singer Type**: ${inputs.singerType}`);
  if (inputs.duration) userParts.push(`- **Target Duration**: ${inputs.duration} seconds`);
  if (inputs.instrumentStyle) userParts.push(`- **Instrument Style**: ${inputs.instrumentStyle}`);
  if (inputs.negativePrompt) userParts.push(`- **What to Avoid**: ${inputs.negativePrompt}`);

  // Include generated content from Step 1 to enrich the prompt
  if (inputs.songConcept) userParts.push(`- **Song Concept**: ${inputs.songConcept}`);
  if (inputs.chorus) userParts.push(`- **Chorus**: ${inputs.chorus}`);
  if (inputs.verses?.length) userParts.push(`- **Verses**: ${inputs.verses.join(' | ')}`);
  if (inputs.bridge) userParts.push(`- **Bridge**: ${inputs.bridge}`);

  if (companyContext) {
    userParts.push(`\n## Brand Context\n${companyContext}`);
  }

  userParts.push(`\nGenerate a detailed, structured Suno AI prompt that captures the full essence of these lyrics and all available musical context. The prompt must be multi-line with clearly labeled sections (Genre, Mood, Tempo, Vocals, Instruments, Production notes, Style notes, Specific requirements). Return ONLY valid JSON.`);

  const userPrompt = userParts.join('\n');

  return {
    systemPrompt,
    userPrompt,
    maxTokens: 2500,
  };
}

// ============================================
// ENHANCEMENT PROMPT (for low-confidence fields)
// ============================================

export function buildAudioContentEnhancementPrompt(
  stageOutput: Record<string, any>,
  lowConfidenceFields: string[]
): PromptResult {
  const systemPrompt = `You are an expert music producer and songwriter AI assistant. You are enhancing specific fields of a song production package that had low confidence in the initial generation.

Return ONLY valid JSON containing ONLY the fields that need enhancement. Do NOT include fields that were not flagged as low-confidence.`;

  const userPrompt = `The following fields had low confidence in the initial generation and need enhancement:

**Low-confidence fields**: ${lowConfidenceFields.join(', ')}

**Current output**:
${JSON.stringify(stageOutput, null, 2)}

Please regenerate ONLY the flagged fields with higher quality and specificity. Return valid JSON with just those fields.`;

  return {
    systemPrompt,
    userPrompt,
    maxTokens: 2000,
  };
}