import { NextResponse } from 'next/server' import { enhancedScreenshotService } from '../../../lib/enhanced-screenshot-simple' import { aiAnalysisService } from '../../../lib/ai-analysis' export async function POST(request) { try { const body = await request.json() const { symbol, layouts, timeframes, selectedLayouts, analyze = true } = body console.log('📊 Enhanced screenshot request:', { symbol, layouts, timeframes, selectedLayouts }) // Prepare configuration for screenshot service const config = { symbol: symbol || 'BTCUSD', timeframe: timeframes?.[0] || '60', // Use first timeframe for now layouts: layouts || selectedLayouts || ['ai'], credentials: { email: process.env.TRADINGVIEW_EMAIL, password: process.env.TRADINGVIEW_PASSWORD } } console.log('🔧 Using config:', config) // Capture screenshots using the working service const screenshots = await enhancedScreenshotService.captureWithLogin(config) console.log('📸 Screenshots captured:', screenshots) let analysis = null // Perform AI analysis if requested and screenshots were captured if (analyze && screenshots.length > 0) { try { console.log('🤖 Starting AI analysis...') // Extract just the filenames from full paths const filenames = screenshots.map(path => path.split('/').pop()) if (filenames.length === 1) { analysis = await aiAnalysisService.analyzeScreenshot(filenames[0]) } else { analysis = await aiAnalysisService.analyzeMultipleScreenshots(filenames) } console.log('✅ AI analysis completed') } catch (analysisError) { console.error('❌ AI analysis failed:', analysisError) // Continue without analysis rather than failing the whole request } } const result = { success: true, 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' : ''}` } 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' } }) }