import { NextResponse } from 'next/server'
import fs from 'fs/promises'
import path from 'path'

export async function GET() {
  try {
    const screenshotsDir = path.join(process.cwd(), 'screenshots')
    
    // Ensure screenshots directory exists
    try {
      await fs.mkdir(screenshotsDir, { recursive: true })
    } catch (error) {
      // Directory might already exist
    }

    // Get list of screenshot files
    let files = []
    try {
      const fileList = await fs.readdir(screenshotsDir)
      files = fileList
        .filter(file => file.endsWith('.png') || file.endsWith('.jpg'))
        .map(file => ({
          name: file,
          path: `/screenshots/${file}`,
          timestamp: Date.now(), // You could get actual file timestamps
          type: file.includes('analysis') ? 'analysis' : 'screenshot'
        }))
        .sort((a, b) => b.timestamp - a.timestamp) // Most recent first
    } catch (error) {
      console.log('No screenshots directory or empty')
    }

    return NextResponse.json({
      success: true,
      screenshots: files,
      total: files.length
    })

  } catch (error) {
    console.error('Screenshots API error:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to get screenshots',
      message: error instanceof Error ? error.message : 'Unknown error'
    }, { status: 500 })
  }
}

export async function POST(request) {
  try {
    const body = await request.json()
    const { action, symbol, timeframe } = body

    // Mock screenshot capture
    const screenshotName = `analysis_${symbol}_${timeframe}_${Date.now()}.png`
    const screenshotPath = `/screenshots/${screenshotName}`

    // In a real implementation, this would capture TradingView
    console.log('📸 Mock screenshot captured:', screenshotPath)

    return NextResponse.json({
      success: true,
      screenshot: {
        name: screenshotName,
        path: screenshotPath,
        timestamp: Date.now(),
        symbol,
        timeframe
      }
    })

  } catch (error) {
    console.error('Screenshot capture error:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to capture screenshot',
      message: error instanceof Error ? error.message : 'Unknown error'
    }, { status: 500 })
  }
}
