import { NextResponse } from 'next/server'
import Replicate from 'replicate'

export async function POST(request: Request) {
  console.log('Prime debug API called')
  
  try {
    const body = await request.json()
    console.log('Request body keys:', Object.keys(body))
    
    const { image, tier, archetype, aura_color, grain, rain } = body
    console.log('Parameters:', { tier, archetype, aura_color, grain, rain, imageSize: image?.length })

    if (!image) {
      console.error('No image provided')
      return NextResponse.json({ error: 'Image is required' }, { status: 400 })
    }

    console.log('Creating Replicate client...')
    const replicateClient = new Replicate({
      auth: process.env.REPLICATE_API_TOKEN,
    })
    
    console.log('Replicate client created, creating prediction...')

    // Create a minimal prediction to test
    const prediction = await replicateClient.predictions.create({
      version: '7762fd07cf82c948538e41f63f77d685e02b063e37e496e96eefd46c929f9bdc',
      input: {
        image,
        prompt: 'test image',
        width: 1024,
        height: 1024,
        num_inference_steps: 25,
      },
    })

    console.log('Prediction created:', prediction.id)

    return NextResponse.json({
      success: true,
      id: prediction.id,
      status: prediction.status
    })
  } catch (error: unknown) {
    console.error('Prime debug error:', error)
    const message = error instanceof Error ? error.message : 'Failed to debug'
    return NextResponse.json({ 
      error: message,
      stack: error instanceof Error ? error.stack : undefined
    }, { status: 500 })
  }
}
