import { NextResponse } from 'next/server' import { aiAnalysisService } from '../../../lib/ai-analysis' import { progressTracker } from '../../../lib/progress-tracker' export async function POST(request) { let sessionId = null try { console.log('๐Ÿ” Enhanced Screenshot API starting...') const body = await request.json() console.log('๐Ÿ” Enhanced Screenshot API request:', body) // PAPER_TRADING PROTECTION: Block requests that could trigger automation if (body.paperTrading || body.enhancedPrompts) { console.log('๐Ÿšจ PAPER_TRADING PROTECTION: Blocking request that could trigger automation') return NextResponse.json({ success: false, error: 'PAPER_TRADING_BLOCK: This API cannot be used from paper trading to prevent real trade execution', safety: true }, { status: 403 }) } const config = { symbol: body.symbol || 'SOLUSD', timeframe: body.timeframe || '240', layouts: body.layouts || ['ai', 'diy'], analyze: body.analyze === true } console.log('๐Ÿ” Processed config:', config) console.log('๐Ÿ” Config.layouts type:', typeof config.layouts) console.log('๐Ÿ” Config.layouts isArray:', Array.isArray(config.layouts)) console.log('๐Ÿ” Config.layouts length:', config.layouts?.length) // Create session for progress tracking const progressSteps = [ { id: 'init', title: 'Initialize', description: 'Starting browser sessions...', status: 'pending' }, { id: 'auth', title: 'Authentication', description: 'Logging into TradingView', status: 'pending' }, { id: 'loading', title: 'Loading Chart', description: 'Loading chart data', status: 'pending' }, { id: 'capture', title: 'Capture Screenshot', description: 'Capturing screenshots', status: 'pending' }, { id: 'analysis', title: 'AI Analysis', description: 'Running AI analysis', status: 'pending' } ] sessionId = `screenshot_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` const progress = progressTracker.createSession(sessionId, progressSteps) config.sessionId = sessionId let screenshots = [] let analysis = null // Capture screenshots using enhanced screenshot service try { console.log('๐Ÿš€ Starting enhanced screenshot capture...') console.log('๐Ÿ“‹ Config being passed to captureWithLogin:', JSON.stringify(config, null, 2)) // Use dynamic import for TypeScript module const { EnhancedScreenshotService } = await import('../../../lib/enhanced-screenshot') const enhancedScreenshotService = new EnhancedScreenshotService() // Use captureWithLogin for proper authentication and session management const screenshotPaths = await enhancedScreenshotService.captureWithLogin(config) console.log('๐Ÿ“ธ Raw screenshotPaths result:', screenshotPaths) console.log('๐Ÿ“ธ Type of screenshotPaths:', typeof screenshotPaths) console.log('๐Ÿ“ธ Is screenshotPaths array?', Array.isArray(screenshotPaths)) screenshots = screenshotPaths || [] console.log('๐Ÿ“ธ Enhanced screenshot capture completed:', screenshots.length, 'files') } catch (screenshotError) { console.error('โŒ Enhanced 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 } // Use dynamic import for TypeScript module and call the correct method const { aiAnalysisService } = await import('../../../lib/ai-analysis') if (screenshots.length === 1) { analysis = await aiAnalysisService.analyzeScreenshot(screenshots[0]) } else { analysis = await aiAnalysisService.analyzeMultipleScreenshots(screenshots) } 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 screenshot service cleanup...') try { // Import aggressive cleanup for browser process cleanup const aggressiveCleanup = (await import('../../../lib/aggressive-cleanup')).default await aggressiveCleanup.forceCleanup() console.log('โœ… FINALLY BLOCK: Aggressive cleanup completed') // Also run process cleanup to ensure no orphaned browsers const { exec } = await import('child_process') const { promisify } = await import('util') const execAsync = promisify(exec) try { await execAsync('pkill -f "chromium|chrome" || true') console.log('โœ… FINALLY BLOCK: Browser process cleanup completed') } catch (cleanupError) { console.log('โš ๏ธ FINALLY BLOCK: Browser process cleanup had minor issues:', cleanupError.message) } 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' } }) }