import { NextRequest, NextResponse } from 'next/server'
import { aiAnalysisService } from '../../../lib/ai-analysis'
import { tradingViewCapture } from '../../../lib/tradingview'
import { settingsManager } from '../../../lib/settings'
import path from 'path'

export async function POST(req: NextRequest) {
  try {
    const { symbol, layouts, timeframe } = 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 })
    }
    
    const baseFilename = `${finalSymbol}_${finalTimeframe}_${Date.now()}`
    const screenshots = await tradingViewCapture.capture(finalSymbol, `${baseFilename}.png`, finalLayouts, finalTimeframe)
    
    let result
    if (screenshots.length === 1) {
      // Single screenshot analysis
      const filename = path.basename(screenshots[0])
      result = await aiAnalysisService.analyzeScreenshot(filename)
    } else {
      // Multiple screenshots analysis
      const filenames = screenshots.map(screenshot => path.basename(screenshot))
      result = await aiAnalysisService.analyzeMultipleScreenshots(filenames)
    }
    
    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 => path.basename(s))
    })
  } catch (e: any) {
    return NextResponse.json({ error: e.message }, { status: 500 })
  }
}
