import pandas as pd
import datetime
import numpy as np
import random


class RiskManager:
    """Manages risk assessment and position sizing for trading decisions.

    Evaluates trading decisions from probability-based signals and applies
    risk management rules including commission calculations and profit targets.
    """

    def __init__(self, commission: float = 0.04):
        """Initialize RiskManager with commission rate.

        Args:
            commission: Commission rate as decimal (default 0.04 = 4%).
        """
        self.commission = commission

    def get_decision(self, probability_decision: dict, price: float, deals: pd.DataFrame = None) -> dict:
        """Evaluate trading decision with risk management rules.

        Args:
            probability_decision: Dictionary containing 'trande' direction from TradeVoter.
            price: Current market price.
            deals: DataFrame of active positions (optional).

        Returns:
            Dictionary with 'decision' ('buy', 'sell', 'none') and additional fields:
                - For 'buy': includes 'amount' field
                - For 'sell': includes 'deals' list of position UUIDs to close
        """
        ans = {}
        ans['decision'] = 'none'

        if probability_decision['trande'] == 'up':
            ans['decision'] = 'buy'
            ans['amount'] = 1

        elif probability_decision['trande'] == 'none':
            ans['decision'] = 'none'

        elif probability_decision['trande'] == 'down':
            if deals is not None:
                for i in range(deals.shape[0]):
                    ans['decision'] = 'none'
                    ans['deals'] = []
                    row = deals.iloc[i]
                    # Check if position is profitable after commission
                    if row.startPrice < price * pow(1 + self.commission, 2):
                        ans['decision'] = 'sell'
                        ans['deals'].append(row.name)

        return ans
