import { NextResponse } from 'next/server'
import { enhancedScreenshotService } from '../../../lib/enhanced-screenshot'
import { aiAnalysisService } from '../../../lib/ai-analysis'
import { progressTracker } from '../../../lib/progress-tracker'

export async function POST(request) {
  try {
    const body = await request.json()
    const { symbol, layouts, timeframe, timeframes, selectedLayouts, analyze = true } = body

    console.log('📊 Enhanced screenshot request:', { symbol, layouts, timeframe, timeframes, selectedLayouts })

    // Generate unique session ID for progress tracking
    const sessionId = `analysis_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    console.log('🔍 Created session ID:', sessionId)

    // Create progress tracking session with initial steps
    const initialSteps = [
      {
        id: 'init',
        title: 'Initializing Analysis',
        description: 'Starting AI-powered trading analysis...',
        status: 'pending'
      },
      {
        id: 'auth',
        title: 'TradingView Authentication',
        description: 'Logging into TradingView accounts',
        status: 'pending'
      },
      {
        id: 'navigation',
        title: 'Chart Navigation',
        description: 'Navigating to chart layouts',
        status: 'pending'
      },
      {
        id: 'loading',
        title: 'Chart Data Loading',
        description: 'Waiting for chart data and indicators',
        status: 'pending'
      },
      {
        id: 'capture',
        title: 'Screenshot Capture',
        description: 'Capturing high-quality screenshots',
        status: 'pending'
      },
      {
        id: 'analysis',
        title: 'AI Analysis',
        description: 'Analyzing screenshots with AI',
        status: 'pending'
      }
    ]

    // Create the progress session
    console.log('🔍 Creating progress session with steps:', initialSteps.length)
    progressTracker.createSession(sessionId, initialSteps)
    console.log('🔍 Progress session created successfully')

    // Mark the start of analysis cycle for cleanup system
    try {
      const { analysisCompletionFlag } = await import('../../../lib/analysis-completion-flag')
      analysisCompletionFlag.startAnalysisCycle(sessionId)
      console.log(`🔍 Analysis cycle started for session: ${sessionId}`)
    } catch (flagError) {
      console.error('Error starting analysis cycle:', flagError)
    }

    // Prepare configuration for screenshot service
    const config = {
      symbol: symbol || 'BTCUSD',
      timeframe: timeframe || timeframes?.[0] || '60', // Use single timeframe, fallback to first of array, then default
      layouts: layouts || selectedLayouts || ['ai'],
      sessionId, // Pass session ID for progress tracking
      credentials: {
        email: process.env.TRADINGVIEW_EMAIL,
        password: process.env.TRADINGVIEW_PASSWORD
      }
    }

    console.log('🔧 Using config:', config)

    let screenshots = []
    let analysis = null
    
    // Perform AI analysis if requested
    if (analyze) {
      try {
        console.log('🤖 Starting automated capture and analysis...')
        const result = await aiAnalysisService.captureAndAnalyzeWithConfig(config, sessionId)
        screenshots = result.screenshots
        analysis = result.analysis
        console.log('✅ Automated capture and analysis completed')
      } catch (analysisError) {
        console.error('❌ Automated capture and analysis failed:', analysisError)
        // Fall back to screenshot only
        screenshots = await enhancedScreenshotService.captureWithLogin(config, sessionId)
      }
    } else {
      // Capture screenshots only
      screenshots = await enhancedScreenshotService.captureWithLogin(config, sessionId)
    }

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

    const result = {
      success: true,
      sessionId, // Return session ID for progress tracking
      timestamp: Date.now(),
      symbol: config.symbol,
      layouts: config.layouts,
      timeframes: [config.timeframe],
      screenshots: screenshots.map(path => ({
        layout: config.layouts[0], // For now, assume one layout
        timeframe: config.timeframe,
        url: `/screenshots/${path.split('/').pop()}`,
        timestamp: Date.now()
      })),
      analysis: analysis,
      message: `Successfully captured ${screenshots.length} screenshot(s)${analysis ? ' with AI analysis' : ''}`
    }

    // Mark analysis as complete for cleanup system
    try {
      const { analysisCompletionFlag } = await import('../../../lib/analysis-completion-flag')
      analysisCompletionFlag.markAnalysisComplete(sessionId)
      console.log(`✅ Analysis marked as complete for session: ${sessionId}`)
    } catch (flagError) {
      console.error('Error marking analysis complete:', flagError)
    }

    // Trigger post-analysis cleanup in development mode
    if (process.env.NODE_ENV === 'development') {
      try {
        const { default: aggressiveCleanup } = await import('../../../lib/aggressive-cleanup')
        // Run cleanup in background, don't block the response
        aggressiveCleanup.runPostAnalysisCleanup().catch(console.error)
      } catch (cleanupError) {
        console.error('Error triggering post-analysis cleanup:', cleanupError)
      }
    }

    return NextResponse.json(result)
  } catch (error) {
    console.error('Enhanced screenshot API error:', error)
    return NextResponse.json(
      { 
        success: false, 
        error: 'Analysis failed',
        message: error.message 
      },
      { status: 500 }
    )
  }
}

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'
    }
  })
}
