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

// Persistent storage for positions using JSON file
const POSITIONS_FILE = path.join(process.cwd(), 'data', 'positions.json')
const TRADES_FILE = path.join(process.cwd(), 'data', 'trades.json')

// Ensure data directory exists
const dataDir = path.join(process.cwd(), 'data')
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true })
}

// Helper functions for persistent storage
function loadPositions() {
  try {
    if (fs.existsSync(POSITIONS_FILE)) {
      const data = fs.readFileSync(POSITIONS_FILE, 'utf8')
      return JSON.parse(data)
    }
  } catch (error) {
    console.error('Error loading positions:', error)
  }
  return []
}

function savePositions(positions) {
  try {
    fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2))
  } catch (error) {
    console.error('Error saving positions:', error)
  }
}

function loadTrades() {
  try {
    if (fs.existsSync(TRADES_FILE)) {
      const data = fs.readFileSync(TRADES_FILE, 'utf8')
      return JSON.parse(data)
    }
  } catch (error) {
    console.error('Error loading trades:', error)
  }
  return []
}

function saveTrades(trades) {
  try {
    fs.writeFileSync(TRADES_FILE, JSON.stringify(trades, null, 2))
  } catch (error) {
    console.error('Error saving trades:', error)
  }
}

export async function GET() {
  try {
    // Load positions from persistent storage
    const activePositions = loadPositions()
    
    // Calculate current P&L for each position using real-time prices
    const updatedPositions = await Promise.all(
      activePositions.map(async (position) => {
        try {
          // Get current price from CoinGecko
          const priceResponse = await fetch(
            `https://api.coingecko.com/api/v3/simple/price?ids=${getCoinGeckoId(position.symbol)}&vs_currencies=usd`
          )
          const priceData = await priceResponse.json()
          const currentPrice = priceData[getCoinGeckoId(position.symbol)]?.usd || position.entryPrice

          // Calculate unrealized P&L
          const priceDiff = currentPrice - position.entryPrice
          const unrealizedPnl = position.side === 'BUY' 
            ? priceDiff * position.amount 
            : -priceDiff * position.amount

          const pnlPercentage = ((currentPrice - position.entryPrice) / position.entryPrice) * 100
          const adjustedPnlPercentage = position.side === 'BUY' ? pnlPercentage : -pnlPercentage

          return {
            ...position,
            currentPrice,
            unrealizedPnl,
            pnlPercentage: adjustedPnlPercentage,
            totalValue: position.amount * currentPrice
          }
        } catch (error) {
          console.error(`Error updating position ${position.id}:`, error)
          return position
        }
      })
    )

    return NextResponse.json({
      success: true,
      positions: updatedPositions,
      totalPositions: updatedPositions.length,
      totalValue: updatedPositions.reduce((sum, pos) => sum + (pos.totalValue || 0), 0),
      totalPnl: updatedPositions.reduce((sum, pos) => sum + (pos.unrealizedPnl || 0), 0)
    })

  } catch (error) {
    console.error('Error fetching positions:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to fetch positions',
      positions: []
    }, { status: 500 })
  }
}

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

    if (action === 'add') {
      // Load existing positions
      const activePositions = loadPositions()
      
      // Add new position
      const newPosition = {
        id: `pos_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`,
        symbol: positionData.symbol,
        side: positionData.side,
        amount: parseFloat(positionData.amount),
        entryPrice: parseFloat(positionData.entryPrice),
        leverage: positionData.leverage || 1,
        timestamp: Date.now(),
        status: 'OPEN',
        stopLoss: positionData.stopLoss ? parseFloat(positionData.stopLoss) : null,
        takeProfit: positionData.takeProfit ? parseFloat(positionData.takeProfit) : null,
        txId: positionData.txId || null
      }

      activePositions.push(newPosition)
      savePositions(activePositions)

      console.log(`✅ Position created: ${newPosition.side} ${newPosition.amount} ${newPosition.symbol}`)

      return NextResponse.json({
        success: true,
        position: newPosition,
        message: `Position opened: ${newPosition.side} ${newPosition.amount} ${newPosition.symbol}`
      })

    } else if (action === 'close') {
      // Load existing positions
      const activePositions = loadPositions()
      
      // Close position by executing reverse trade
      const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
      
      if (positionIndex === -1) {
        return NextResponse.json({
          success: false,
          error: 'Position not found'
        }, { status: 404 })
      }

      const position = activePositions[positionIndex]
      const exitPrice = positionData.exitPrice || position.currentPrice || position.entryPrice
      
      // Calculate P&L
      const priceDiff = exitPrice - position.entryPrice
      const realizedPnl = position.side === 'BUY' 
        ? priceDiff * position.amount 
        : -priceDiff * position.amount

      console.log(`🔄 Closing position ${positionId}: ${position.side} ${position.amount} ${position.symbol}`)
      console.log(`💰 Entry: $${position.entryPrice}, Exit: $${exitPrice}, P&L: $${realizedPnl.toFixed(4)}`)

      try {
        // Add closing trade to history
        const existingTrades = loadTrades()
        const closingTrade = {
          id: `trade_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`,
          symbol: position.symbol,
          side: position.side === 'BUY' ? 'SELL' : 'BUY', // Reverse side for closing
          amount: position.amount,
          price: exitPrice,
          type: 'market',
          status: 'executed',
          timestamp: Date.now(),
          txId: `close_${position.id}`,
          fee: 0,
          pnl: realizedPnl,
          dex: 'SIMULATION',
          notes: `Closed position ${position.id} with P&L $${realizedPnl.toFixed(4)}`
        }
        
        existingTrades.push(closingTrade)
        
        // Keep only last 100 trades
        if (existingTrades.length > 100) {
          existingTrades.splice(0, existingTrades.length - 100)
        }
        
        saveTrades(existingTrades)
        console.log('✅ Closing trade added to history')

        console.log(`💰 Position closed with P&L: $${realizedPnl.toFixed(4)}`)

        // Update position status and remove from active
        position.status = 'CLOSED'
        position.closedAt = Date.now()
        position.exitPrice = exitPrice
        position.realizedPnl = realizedPnl
        position.closeTxId = closingTrade.txId
        
        // Remove from active positions
        activePositions.splice(positionIndex, 1)
        savePositions(activePositions)

        return NextResponse.json({
          success: true,
          position: position,
          closingTrade: closingTrade,
          realizedPnl: realizedPnl,
          message: `Position closed: ${position.symbol} with P&L ${realizedPnl >= 0 ? '+' : ''}$${realizedPnl.toFixed(4)}`
        })

      } catch (error) {
        console.error('Error closing position:', error)
        
        // Fallback: just remove position
        position.status = 'CLOSED'
        position.closedAt = Date.now()
        position.exitPrice = exitPrice
        position.realizedPnl = realizedPnl
        
        activePositions.splice(positionIndex, 1)
        savePositions(activePositions)

        return NextResponse.json({
          success: true,
          position: position,
          realizedPnl: realizedPnl,
          message: `Position closed (fallback): ${position.symbol}`,
          warning: 'Failed to add to trade history'
        })
      }

    } else if (action === 'update') {
      // Load existing positions
      const activePositions = loadPositions()
      
      // Update position (for SL/TP changes)
      const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
      
      if (positionIndex === -1) {
        return NextResponse.json({
          success: false,
          error: 'Position not found'
        }, { status: 404 })
      }

      const position = activePositions[positionIndex]
      if (positionData.stopLoss !== undefined) position.stopLoss = positionData.stopLoss
      if (positionData.takeProfit !== undefined) position.takeProfit = positionData.takeProfit

      savePositions(activePositions)

      return NextResponse.json({
        success: true,
        position,
        message: 'Position updated successfully'
      })
    }

    return NextResponse.json({
      success: false,
      error: 'Invalid action'
    }, { status: 400 })

  } catch (error) {
    console.error('Error managing position:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to manage position'
    }, { status: 500 })
  }
}

// Helper function to map symbols to CoinGecko IDs
function getCoinGeckoId(symbol) {
  const mapping = {
    'SOL': 'solana',
    'SOLUSD': 'solana',
    'BTC': 'bitcoin',
    'ETH': 'ethereum',
    'USDC': 'usd-coin',
    'USDT': 'tether',
    'RAY': 'raydium',
    'ORCA': 'orca'
  }
  return mapping[symbol.replace('USD', '')] || 'solana'
}
