import { Agent } from './Agent';

export class RiskManager {
  evaluateTradeRisk(agent: Agent, tradeSignal: { positionSize: number, stopLoss: number }) {
    const balance = agent.economicTracker.balance;
    const status = agent.economicTracker.getSurvivalStatus();
    const maxLoss = tradeSignal.positionSize * tradeSignal.stopLoss;

    const assessment = {
      approved: false,
      riskLevel: 'unknown',
      maxPositionSize: 0,
      reason: ''
    };

    if (status === '💀 bankrupt') {
      assessment.reason = 'Agent bankrupt, trading forbidden';
      return assessment;
    }

    let maxRiskRatio = 0;
    if (status === '🔴 critical') maxRiskRatio = 0.01;
    else if (status === '⚠️ struggling') maxRiskRatio = 0.03;
    else if (status === '💪 stable') maxRiskRatio = 0.05;
    else if (status === '🚀 thriving') maxRiskRatio = 0.10;

    const maxRisk = balance * maxRiskRatio;
    if (maxLoss > maxRisk) {
      assessment.reason = `Risk too high, max allowed loss: $${maxRisk.toFixed(2)}`;
      assessment.maxPositionSize = maxRisk / tradeSignal.stopLoss;
    } else {
      assessment.approved = true;
      assessment.riskLevel = maxRiskRatio <= 0.03 ? 'low' : maxRiskRatio <= 0.05 ? 'medium' : 'high';
      assessment.maxPositionSize = tradeSignal.positionSize;
    }

    return assessment;
  }
}
