import { NextRequest, NextResponse } from 'next/server'

export interface NarrativeRequest {
  basePrompt: string
  title: string
  description: string
  imageCount: number
  style: string
  characters?: string
  items?: string
}

export interface NarrativeResponse {
  prompts: string[]
}

export async function POST(request: NextRequest) {
  try {
    const body: NarrativeRequest = await request.json()
    
    const {
      basePrompt,
      title,
      description,
      imageCount,
      style,
      characters = '',
      items = '',
    } = body

    if (!basePrompt || !title || !description || imageCount <= 0) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      )
    }

    // Generate narrative progression
    const prompts = generateNarrativeProgression({
      basePrompt,
      title,
      description,
      imageCount,
      style,
      characters,
      items,
    })

    return NextResponse.json({
      prompts,
      success: true,
    })

  } catch (error) {
    console.error('Narrative generation error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

function generateNarrativeProgression(config: NarrativeRequest): string[] {
  const {
    basePrompt,
    title,
    description,
    imageCount,
    style,
    characters,
    items,
  } = config

  const prompts: string[] = []

  // Define narrative structure based on image count
  const narrativeStructure = getNarrativeStructure(imageCount)

  // Generate prompts for each narrative stage
  for (let i = 0; i < imageCount; i++) {
    const stage = narrativeStructure[i] || narrativeStructure[narrativeStructure.length - 1]
    
    const prompt = generateStagePrompt({
      stage,
      basePrompt,
      title,
      description,
      style,
      characters,
      items,
      index: i,
      total: imageCount,
    })

    prompts.push(prompt)
  }

  return prompts
}

function getNarrativeStructure(imageCount: number): string[] {
  if (imageCount <= 3) {
    return ['introduction', 'development', 'climax']
  } else if (imageCount <= 5) {
    return [
      'introduction',
      'rising_action',
      'midpoint',
      'climax',
      'resolution'
    ]
  } else if (imageCount <= 8) {
    return [
      'introduction',
      'setup',
      'rising_action_1',
      'rising_action_2',
      'midpoint',
      'climax',
      'falling_action',
      'resolution'
    ]
  } else {
    // For longer series, use a more detailed structure
    const structure = [
      'introduction',
      'world_building',
      'character_introduction',
      'initial_challenge',
      'rising_action_1',
      'rising_action_2',
      'midpoint_twist',
      'climax_buildup',
      'climax',
      'resolution',
      'epilogue'
    ]

    // Repeat middle elements for longer series
    while (structure.length < imageCount) {
      structure.splice(-2, 0, `development_${structure.length}`)
    }

    return structure.slice(0, imageCount)
  }
}

function generateStagePrompt(config: {
  stage: string
  basePrompt: string
  title: string
  description: string
  style: string
  characters: string
  items: string
  index: number
  total: number
}): string {
  const {
    stage,
    basePrompt,
    title,
    description,
    style,
    characters,
    items,
    index,
    total,
  } = config

  // Stage-specific templates
  const stageTemplates: Record<string, string[]> = {
    introduction: [
      `Wide establishing shot of ${title} with ${description}. ${characters ? `Featuring ${characters}.` : ''} ${items ? `With ${items} visible.` : ''} ${style} style, atmospheric lighting.`,
      `Close-up introduction to the main elements of ${title}, showcasing ${description}. ${characters ? `Focus on ${characters}.` : ''} ${style} aesthetic.`,
      `Panoramic view of the ${title} scene, ${description}. Epic scale with ${characters} ${items ? `and ${items}` : ''} in ${style} style.`
    ],
    rising_action: [
      `${title}: Building tension as ${description}. ${characters} ${items ? `interacting with ${items}` : ''}. Dramatic composition in ${style} style.`,
      `Progressive development of ${title}, ${description}. ${characters} showing character development. ${items} becoming more prominent. ${style} visual style.`,
      `Action sequence in ${title}, ${description}. ${characters} in motion with ${items}. Dynamic angles and ${style} rendering.`
    ],
    climax: [
      `Dramatic climax of ${title}: ${description}. ${characters} at peak action with ${items}. High contrast lighting, ${style} style.`,
      `Intense climax scene showing ${title}: ${description}. ${characters} in decisive moment with ${items}. Cinematic ${style} composition.`,
      `Peak action in ${title}: ${description}. ${characters} and ${items} in dramatic confrontation. Epic scale with ${style} aesthetic.`
    ],
    resolution: [
      `Resolution of ${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in peaceful setting. Warm lighting, ${style} style.`,
      `Conclusion of ${title}: ${description}. ${characters} ${items ? `and ${items}` : ''} in final arrangement. Serene composition, ${style} aesthetic.`,
      `Final scene of ${title}: ${description}. ${characters} ${items ? `and ${items}` : ''} in satisfying conclusion. ${style} style with atmospheric mood.`
    ],
    midpoint: [
      `Midpoint twist in ${title}: ${description}. ${characters} facing unexpected challenge with ${items}. ${style} style with dramatic lighting.`,
      `Turning point in ${title}: ${description}. ${characters} experiencing major development with ${items}. ${style} visual approach.`
    ],
    development: [
      `Development scene in ${title}: ${description}. ${characters} evolving story with ${items}. ${style} style with detailed composition.`,
      `Progressive scene of ${title}: ${description}. ${characters} advancing narrative with ${items}. ${style} aesthetic with atmospheric elements.`
    ],
    world_building: [
      `World-building scene for ${title}: ${description}. Detailed environment showing ${characters} ${items ? `with ${items}` : ''} in ${style} style.`,
      `Environmental storytelling in ${title}: ${description}. Rich world details featuring ${characters} ${items ? `and ${items}` : ''}. ${style} aesthetic.`
    ],
    character_introduction: [
      `Character introduction in ${title}: ${description}. Focus on ${characters} ${items ? `with ${items}` : ''} in ${style} style.`,
      `Detailed character presentation in ${title}: ${description}. ${characters} ${items ? `interacting with ${items}` : ''}. ${style} visual treatment.`
    ],
    initial_challenge: [
      `Initial challenge in ${title}: ${description}. ${characters} facing ${items} in ${style} style.`,
      `First obstacle scene: ${title} with ${description}. ${characters} encountering ${items}. ${style} composition.`
    ],
    falling_action: [
      `Falling action in ${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in aftermath. ${style} style with reflective mood.`,
      `Resolution aftermath: ${title} - ${description}. ${characters} ${items ? `and ${items}` : ''} in peaceful setting. ${style} aesthetic.`
    ],
    epilogue: [
      `Epilogue scene for ${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in final moments. ${style} style with nostalgic atmosphere.`,
      `Closing scene of ${title}: ${description}. ${characters} ${items ? `and ${items}` : ''} in satisfying conclusion. ${style} visual style.`
    ]
  }

  // Default template for unknown stages
  const defaultTemplates = [
    `${title}: ${description}. ${characters} ${items ? `with ${items}` : ''} in ${style} style.`,
    `Scene from ${title}: ${description}. Featuring ${characters} ${items ? `and ${items}` : ''}. ${style} aesthetic.`,
    `${title} scene: ${description}. ${characters} ${items ? `interacting with ${items}` : ''}. ${style} visual approach.`
  ]

  // Get templates for the current stage
  const templates = stageTemplates[stage] || defaultTemplates

  // Select template based on index for variety
  const templateIndex = index % templates.length
  let prompt = templates[templateIndex]

  // Add progress-specific details
  const progress = (index + 1) / total
  if (progress < 0.3) {
    prompt += ' Beginning of the journey, hopeful atmosphere.'
  } else if (progress < 0.7) {
    prompt += ' Mid-journey, building intensity and drama.'
  } else {
    prompt += ' Conclusion, satisfying resolution and closure.'
  }

  return prompt
}