import { NextResponse } from 'next/server'
import { superiorScreenshotService } from '../../../lib/superior-screenshot-service'
import { aiAnalysisService } from '../../../lib/ai-analysis'
import { progressTracker } from '../../../lib/progress-tracker'

export async function POST(request) {
  let sessionId = null
  
  try {
    const body = await request.json()
    console.log('🔍 Enhanced Screenshot API request:', body)

    const config = {
      symbol: body.symbol || 'SOLUSD',
      timeframe: body.timeframe || '240',
      layouts: body.layouts || ['ai', 'diy'],
      analyze: body.analyze === true
    }

    // Create session for progress tracking
    sessionId = progressTracker.createSession()
    config.sessionId = sessionId
    
    console.log(`🔍 Created session ${sessionId} for enhanced screenshot`)

    // Initialize progress steps
    progressTracker.initializeSteps(sessionId, [
      { id: 'init', name: 'Initialize', status: 'active' },
      { id: 'auth', name: 'Authentication', status: 'pending' },
      { id: 'loading', name: 'Loading Chart', status: 'pending' },
      { id: 'capture', name: 'Capture Screenshot', status: 'pending' },
      { id: 'analysis', name: 'AI Analysis', status: 'pending' }
    ])

    let screenshots = []
    let analysis = null

    // Capture screenshots using superior parallel technique
    try {
      console.log('🚀 Starting superior screenshot capture...')
      
      // Use single timeframe capture for backwards compatibility
      const screenshotPaths = await superiorScreenshotService.captureQuick(
        config.symbol, 
        config.timeframe, 
        config.layouts
      )
      
      screenshots = screenshotPaths
      console.log('📸 Superior screenshot capture completed:', screenshots.length, 'files')
    } catch (screenshotError) {
      console.error('❌ Superior screenshot capture failed:', screenshotError)
      throw new Error(`Screenshot capture failed: ${screenshotError.message}`)
    }

    // Run AI analysis if requested
    if (config.analyze && screenshots.length > 0) {
      try {
        console.log('🤖 Starting AI analysis...')
        progressTracker.updateStep(sessionId, 'analysis', 'active', 'Analyzing screenshots...')
        
        const analysisConfig = {
          sessionId,
          screenshots,
          symbol: config.symbol,
          timeframe: config.timeframe,
          layouts: config.layouts
        }
        
        analysis = await aiAnalysisService.analyzeScreenshots(analysisConfig)
        
        if (analysis) {
          progressTracker.updateStep(sessionId, 'analysis', 'completed', 'Analysis completed successfully')
          console.log('✅ AI analysis completed')
        } else {
          progressTracker.updateStep(sessionId, 'analysis', 'error', 'Analysis failed to return results')
          console.warn('⚠️ AI analysis completed but returned no results')
        }
        
      } catch (analysisError) {
        console.error('❌ AI analysis failed:', analysisError)
        progressTracker.updateStep(sessionId, 'analysis', 'error', analysisError.message)
        // Don't throw - return partial results with screenshots
        analysis = { error: analysisError.message }
      }
    }

    console.log('📸 Final screenshots:', screenshots)

    const result = {
      success: true,
      sessionId,
      timestamp: Date.now(),
      symbol: config.symbol,
      layouts: config.layouts,
      timeframes: [config.timeframe],
      screenshots,
      analysis,
      message: `Successfully captured ${screenshots.length} screenshot(s)${config.analyze ? ' with AI analysis' : ''}`
    }

    console.log('✅ Enhanced screenshot API completed successfully')
    return NextResponse.json(result)

  } catch (error) {
    console.error('❌ Enhanced screenshot API error:', error)
    
    if (sessionId) {
      // Mark any active step as error
      const progress = progressTracker.getProgress(sessionId)
      if (progress) {
        const activeStep = progress.steps.find(step => step.status === 'active')
        if (activeStep) {
          progressTracker.updateStep(sessionId, activeStep.id, 'error', error.message)
        }
      }
    }

    return NextResponse.json({
      success: false,
      error: error.message,
      timestamp: Date.now(),
      sessionId
    }, { status: 500 })
    
  } finally {
    // CRITICAL: Always run cleanup in finally block
    console.log('🧹 FINALLY BLOCK: Running superior screenshot service cleanup...')
    
    try {
      // Force cleanup all browser sessions (API-managed, no action needed)
      await superiorScreenshotService.cleanup()
      console.log('✅ FINALLY BLOCK: Superior screenshot service cleanup completed')
      
      // Also run aggressive cleanup to ensure no processes remain
      const { automatedCleanupService } = await import('../../../lib/automated-cleanup-service')
      await automatedCleanupService.forceCleanup()
      console.log('✅ FINALLY BLOCK: Automated cleanup completed')
      
    } catch (cleanupError) {
      console.error('❌ FINALLY BLOCK: Error during cleanup:', cleanupError)
    }
    
    // Clean up progress session after delay to allow frontend to read final state
    if (sessionId) {
      setTimeout(() => {
        try {
          progressTracker.deleteSession(sessionId)
          console.log(`🗑️ Cleaned up session ${sessionId}`)
        } catch (sessionCleanupError) {
          console.error('Error cleaning up session:', sessionCleanupError)
        }
      }, 30000) // 30 second delay
    }
  }
}

export async function GET() {
  return NextResponse.json({
    message: 'Enhanced Screenshot API - use POST method for analysis',
    endpoints: {
      POST: '/api/enhanced-screenshot - Run analysis with parameters'
    }
  })
}
