import { SurvivalStatus } from './types';

export class EconomicTracker {
  balance: number;
  tokenCosts: number = 0;
  tradeCosts: number = 0;
  realizedPnl: number = 0;

  private thresholds: {
    thriving: number;
    stable: number;
    struggling: number;
    bankrupt: number;
  };

  constructor(
    initialCapital: number = 10000.0,
    private tokenCostPer1mInput: number = 2.5,
    private tokenCostPer1mOutput: number = 10.0,
    private tradeFeeRate: number = 0.001
  ) {
    this.balance = initialCapital;
    this.thresholds = {
      thriving: initialCapital * 1.5,
      stable: initialCapital * 1.1,
      struggling: initialCapital * 0.8,
      bankrupt: initialCapital * 0.3
    };
  }

  calculateDecisionCost(tokensInput: number, tokensOutput: number, marketDataCalls: number): number {
    const llmCost = (tokensInput / 1e6) * this.tokenCostPer1mInput + 
                    (tokensOutput / 1e6) * this.tokenCostPer1mOutput;
    const dataCost = marketDataCalls * 0.01;
    const totalCost = llmCost + dataCost;
    
    this.tokenCosts += totalCost;
    this.balance -= totalCost;
    
    return totalCost;
  }

  calculateTradeCost(tradeValue: number, isWin: boolean, winAmount: number = 0, lossAmount: number = 0) {
    const fee = tradeValue * this.tradeFeeRate;
    this.tradeCosts += fee;
    this.balance -= fee;

    const pnl = winAmount - lossAmount - fee;
    this.realizedPnl += pnl;
    this.balance += pnl;

    return {
      fee,
      pnl,
      balance: this.balance,
      status: this.getSurvivalStatus()
    };
  }

  getSurvivalStatus(): SurvivalStatus {
    if (this.balance >= this.thresholds.thriving) return '🚀 thriving';
    if (this.balance >= this.thresholds.stable) return '💪 stable';
    if (this.balance >= this.thresholds.struggling) return '⚠️ struggling';
    if (this.balance >= this.thresholds.bankrupt) return '🔴 critical';
    return '💀 bankrupt';
  }
}
