import fs from 'fs'
import path from 'path'

// Persistent storage for wallet balance changes
const WALLET_TRANSACTIONS_FILE = path.join(process.cwd(), 'data', 'wallet-transactions.json')

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

// Helper functions for wallet transaction tracking
function loadWalletTransactions() {
  try {
    if (fs.existsSync(WALLET_TRANSACTIONS_FILE)) {
      const data = fs.readFileSync(WALLET_TRANSACTIONS_FILE, 'utf8')
      return JSON.parse(data)
    }
  } catch (error) {
    console.error('Error loading wallet transactions:', error)
  }
  return []
}

function saveWalletTransactions(transactions) {
  try {
    fs.writeFileSync(WALLET_TRANSACTIONS_FILE, JSON.stringify(transactions, null, 2))
  } catch (error) {
    console.error('Error saving wallet transactions:', error)
  }
}

export function addWalletTransaction(transaction) {
  const transactions = loadWalletTransactions()
  
  const newTransaction = {
    id: `wtx_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`,
    type: transaction.type, // 'trade_open', 'trade_close', 'swap', etc.
    symbol: transaction.symbol,
    amount: transaction.amount, // Positive = received, Negative = sent
    usdValue: transaction.usdValue,
    timestamp: Date.now(),
    txId: transaction.txId,
    positionId: transaction.positionId || null,
    notes: transaction.notes || null
  }
  
  transactions.push(newTransaction)
  
  // Keep only last 500 transactions
  if (transactions.length > 500) {
    transactions.splice(0, transactions.length - 500)
  }
  
  saveWalletTransactions(transactions)
  
  console.log('💼 Wallet transaction recorded:', newTransaction)
  return newTransaction
}

export function getWalletTransactions() {
  return loadWalletTransactions()
}

export function getWalletBalanceAdjustment() {
  const transactions = loadWalletTransactions()
  
  // Calculate total adjustments by symbol
  const adjustments = {}
  
  transactions.forEach(tx => {
    if (!adjustments[tx.symbol]) {
      adjustments[tx.symbol] = { amount: 0, usdValue: 0 }
    }
    adjustments[tx.symbol].amount += tx.amount
    adjustments[tx.symbol].usdValue += tx.usdValue
  })
  
  return adjustments
}

export function clearWalletTransactions() {
  saveWalletTransactions([])
  console.log('💼 Wallet transactions cleared')
}
