import { NextRequest, NextResponse } from 'next/server' import { aiAnalysisService } from '../../../lib/ai-analysis' import { enhancedScreenshotService } from '../../../lib/enhanced-screenshot' import { settingsManager } from '../../../lib/settings' import path from 'path' import fs from 'fs' export async function POST(req: NextRequest) { try { const { symbol, layouts, timeframe, useExisting } = await req.json() // Load current settings const settings = await settingsManager.loadSettings() // Use provided values or fall back to saved settings const finalSymbol = symbol || settings.symbol const finalTimeframe = timeframe || settings.timeframe const finalLayouts = layouts || settings.layouts if (!finalSymbol) { return NextResponse.json({ error: 'Missing symbol' }, { status: 400 }) } let screenshots: string[] = [] // If useExisting is true, find existing screenshots if (useExisting) { console.log('Using existing screenshots for analysis...') const screenshotsDir = path.join(process.cwd(), 'screenshots') const allFiles = await fs.promises.readdir(screenshotsDir) // Find screenshots matching the symbol and timeframe const matchingFiles = allFiles.filter(file => file.includes(finalSymbol) && file.includes(finalTimeframe) && file.endsWith('.png') && !file.includes('debug') ) if (matchingFiles.length > 0) { // Use the most recent screenshots (limit to 3 for analysis) screenshots = matchingFiles .sort((a, b) => b.localeCompare(a)) // Sort by name (which includes timestamp) .slice(0, 3) .map(file => path.join(screenshotsDir, file)) } else { return NextResponse.json({ error: `No existing screenshots found for ${finalSymbol} ${finalTimeframe}` }, { status: 404 }) } } else { // Original behavior - capture new screenshots screenshots = await enhancedScreenshotService.captureWithLogin({ symbol: finalSymbol, timeframe: finalTimeframe, layouts: finalLayouts }) } let result // For now, always use single screenshot analysis to debug the issue if (screenshots.length > 0) { // Always use single screenshot analysis - get the first/most recent screenshot const filename = path.basename(screenshots[0]) console.log(`Analyzing single screenshot: ${filename}`) result = await aiAnalysisService.analyzeScreenshot(filename) } else { return NextResponse.json({ error: 'No screenshots available for analysis' }, { status: 404 }) } if (!result) { return NextResponse.json({ error: 'Analysis failed' }, { status: 500 }) } return NextResponse.json({ ...result, layoutsAnalyzed: finalLayouts, settings: { symbol: finalSymbol, timeframe: finalTimeframe, layouts: finalLayouts }, screenshots: screenshots.map((s: string) => path.basename(s)), usedExisting: useExisting || false }) } catch (e: any) { return NextResponse.json({ error: e.message }, { status: 500 }) } }