import logging
from binance.client import Client
from binance.exceptions import BinanceAPIException

class OrderExecutor:
    def __init__(self, api_key, api_secret, testnet=True):
        self.client = Client(api_key, api_secret, testnet=testnet)
        self.testnet = testnet

    def get_balance(self, asset="USDT"):
        try:
            balance = self.client.get_asset_balance(asset=asset)
            return float(balance['free'])
        except Exception as e:
            logging.error(f"Error fetching balance: {e}")
            return 0.0

    def get_portfolio_balances(self):
        try:
            account = self.client.get_account()
            balances = {}
            for bal in account['balances']:
                free = float(bal['free'])
                locked = float(bal['locked'])
                total = free + locked
                if total > 0:
                    balances[bal['asset']] = {
                        'free': free,
                        'locked': locked,
                        'total': total
                    }
            return balances
        except Exception as e:
            logging.error(f"Error fetching portfolio: {e}")
            return {}

    def execute_market_buy(self, symbol, quantity):
        try:
            logging.info(f"Executing MARKET BUY for {symbol}, quantity: {quantity}")
            order = self.client.order_market_buy(symbol=symbol, quantity=quantity)
            return order
        except BinanceAPIException as e:
            logging.error(f"Binance API Error on BUY: {e}")
            return None

    def execute_market_sell(self, symbol, quantity):
        try:
            logging.info(f"Executing MARKET SELL for {symbol}, quantity: {quantity}")
            order = self.client.order_market_sell(symbol=symbol, quantity=quantity)
            return order
        except BinanceAPIException as e:
            logging.error(f"Binance API Error on SELL: {e}")
            return None

    def create_oco_order(self, symbol, quantity, stop_price, take_profit_price):
        try:
            logging.info(f"Creating OCO for {symbol}: SL {stop_price}, TP {take_profit_price}")
            order = self.client.create_oco_order(
                symbol=symbol,
                side='SELL',
                quantity=quantity,
                price=str(take_profit_price),
                stopPrice=str(stop_price),
                stopLimitPrice=str(stop_price),
                stopLimitTimeInForce='GTC'
            )
            return order
        except BinanceAPIException as e:
            logging.error(f"Binance API Error on OCO: {e}")
            return None
