import json
import logging
import os

class RiskManager:
    def __init__(self, config, data_path="c:/Program Files/Ampps/www/winner/trading-bot/data"):
        self.config = config
        self.data_path = data_path
        self.performance_file = os.path.join(data_path, "performance.json")
        self.trades_log = os.path.join(data_path, "trades_log.json")
        self.daily_pnl = 0.0
        self.open_positions = []
        self.load_performance()

    def load_performance(self):
        if os.path.exists(self.performance_file):
            with open(self.performance_file, 'r') as f:
                self.performance = json.load(f)
        else:
            self.performance = {"total_pnl": 0.0, "daily_pnl": 0.0, "total_trades": 0}

    def save_performance(self):
        with open(self.performance_file, 'w') as f:
            json.dump(self.performance, f, indent=4)

    def calculate_position_size(self, balance):
        max_pct = self.config['risk_management']['max_pos_size_pct']
        return balance * (max_pct / 100.0)

    def can_open_position(self, current_positions_count):
        if current_positions_count >= self.config['bot_settings']['max_positions']:
            logging.warning("Max positions reached.")
            return False
            
        if self.performance['daily_pnl'] < -self.config['risk_management']['max_daily_loss_pct']:
            logging.critical("Max daily loss reached. Trading halted.")
            return False
            
        return True

    def log_trade(self, trade_data):
        trades = []
        if os.path.exists(self.trades_log):
            with open(self.trades_log, 'r') as f:
                trades = json.load(f)
        
        trades.append(trade_data)
        with open(self.trades_log, 'w') as f:
            json.dump(trades, f, indent=4)
            
        self.performance['total_trades'] += 1
        self.performance['total_pnl'] += trade_data.get('pnl', 0.0)
        self.performance['daily_pnl'] += trade_data.get('pnl', 0.0)
        self.save_performance()
