import { NextResponse } from 'next/server'

export async function POST() {
  try {
    console.log('🚨 EMERGENCY STOP INITIATED')
    
    const results = {
      automationStopped: false,
      processesKilled: false,
      cleanupCompleted: false,
      errors: []
    }
    
    // 1. Stop automation normally first
    try {
      const stopResponse = await fetch('http://localhost:3000/api/automation/stop', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      })
      
      if (stopResponse.ok) {
        results.automationStopped = true
        console.log('✅ Automation stopped successfully')
      }
    } catch (error) {
      results.errors.push(`Automation stop failed: ${error.message}`)
      console.error('❌ Automation stop failed:', error)
    }
    
    // 2. Kill background processes
    try {
      const { exec } = require('child_process')
      const util = require('util')
      const execAsync = util.promisify(exec)
      
      // Kill Chromium/Chrome processes
      try {
        await execAsync('pkill -f "chrome|chromium" 2>/dev/null || true')
        console.log('🔫 Chrome/Chromium processes terminated')
      } catch (e) {
        console.log('ℹ️ No Chrome processes to kill')
      }
      
      // Kill any screenshot services
      try {
        await execAsync('pkill -f "screenshot|puppeteer" 2>/dev/null || true')
        console.log('🔫 Screenshot processes terminated')
      } catch (e) {
        console.log('ℹ️ No screenshot processes to kill')
      }
      
      results.processesKilled = true
    } catch (error) {
      results.errors.push(`Process cleanup failed: ${error.message}`)
      console.error('❌ Process cleanup failed:', error)
    }
    
    // 3. Cleanup temporary files
    try {
      const fs = require('fs').promises
      const path = require('path')
      
      // Clean up screenshot directories
      const tempDirs = [
        '/tmp/trading-screenshots',
        '/app/screenshots',
        '/app/temp'
      ]
      
      for (const dir of tempDirs) {
        try {
          await fs.rmdir(dir, { recursive: true })
          console.log(`🧹 Cleaned up ${dir}`)
        } catch (e) {
          // Directory doesn't exist or already clean
        }
      }
      
      results.cleanupCompleted = true
    } catch (error) {
      results.errors.push(`Cleanup failed: ${error.message}`)
      console.error('❌ Cleanup failed:', error)
    }
    
    console.log('🚨 EMERGENCY STOP COMPLETED')
    console.log('Results:', results)
    
    return NextResponse.json({
      success: true,
      message: 'Emergency stop completed',
      results,
      timestamp: new Date().toISOString()
    })
    
  } catch (error) {
    console.error('🚨 EMERGENCY STOP ERROR:', error)
    
    return NextResponse.json({
      success: false,
      error: 'Emergency stop failed',
      message: error.message,
      timestamp: new Date().toISOString()
    }, { status: 500 })
  }
}

export async function GET() {
  return NextResponse.json({
    message: 'Emergency Stop API - use POST method to trigger emergency stop',
    description: 'Immediately stops all automation processes and cleans up resources'
  })
}
