import logging
from zerodha.zerodha_ticker import KiteTicker
from pymongo import MongoClient

# client = MongoClient("mongodb://192.168.31.176:27017/")
# database = client["zerodha_test"]

client = MongoClient("mongodb://jenya:DJenya$Mongo%40St0ckDB@127.0.0.1:27017/")
database = client["trade_iq"]
collection = database["zerodha_instruments"]

class Portfolio:
    def __init__(self, symbol, cash_balance=100000):
        self.cash_balance = cash_balance
        self.money_end = cash_balance
        self.total_investment = [0]
        self.symbol = symbol
        self.investment = {}
        self.holdings = {}

    def buy_stock(self, buy_quantity, buy_price, transaction_cost=0.0375):
        allocated_money = int(buy_quantity) * buy_price
        if allocated_money <= self.cash_balance:
            self.money_end -= (allocated_money + (transaction_cost * allocated_money))
            if self.symbol not in self.investment:
                self.investment[self.symbol] = {'Total': allocated_money, 'Quantity': int(buy_quantity)}
                self.total_investment.append(allocated_money + self.total_investment[-1])
            else:
                self.total_investment.append(allocated_money + self.total_investment[-1])
                self.investment[self.symbol]['Total'] += allocated_money
                self.investment[self.symbol]['Quantity'] += int(buy_quantity)

            if self.symbol not in self.holdings:
                self.holdings[self.symbol] = {'Quantity': round(int(int(buy_quantity)), 2), 'Buy Price': round(buy_price, 2), 'Invested': round(allocated_money, 2)}
            else:
                self.holdings[self.symbol]['Quantity'] += int(buy_quantity)
                self.holdings[self.symbol]['Invested'] += allocated_money

            print(f"Bought {buy_quantity} shares of {self.symbol.upper()} at ${buy_price} each.")
        else:
            print(f"Insufficient Balance!, Order cannot be executed for {self.symbol.upper()}")

    def sell_stock(self, sell_quantity, sell_price, transaction_cost=0.0375):
        if self.symbol in self.holdings:
            if self.holdings[self.symbol]['Quantity'] >= sell_quantity:
                sale_proceeds = sell_quantity * sell_price
                self.cash_balance += (sale_proceeds - (transaction_cost * sale_proceeds))
                self.holdings[self.symbol]['Quantity'] -= sell_quantity
                self.holdings[self.symbol]['Invested'] -= (sell_quantity * self.holdings[self.symbol]['Buy Price'])
                if self.holdings[self.symbol]['Quantity'] == 0:
                    del self.holdings[self.symbol]  # This will remove the stock from holding if all the quantity has been sold
            else:
                print(f"Insufficient quantity of {self.symbol.upper()} shares to sell.")
        else:
            print(f"You do not hold any {self.symbol.upper()} shares to sell.")

    def portfolio_value(self):
        total_value = self.cash_balance
        for self.symbol, holding in self.holdings.items():
            current_price = self.get_current_price()
            total_value += current_price * holding['Quantity']
        return total_value

    def get_current_price(self):  # We will connect our broker here
        # Broker_info
        '''
        socket = wss://ws.zerodha.com/?api_key=kitefront&user_id=GMG829&enctoken=CXBxri9sLiSZJb%2FPSwA823fdkY5VO4vPKgpbwUM5ynGDaGk6g0nNp%2BjJdX1iU5CHX4hNgpFLF0vdpu8Ac%2F8lOZomrmi9HLs00dvI9xerJ1BhfksFbWGmXw%3D%3D&uid=1707971555312&user-agent=kite3-web&version=3.0.0&a=mode
        '''
        # Connect the Database where Instrument_Token is stored
        if self.symbol != '':
            currentLTP_list = []

            # GET Instrument Token from the DB
            result = collection.find_one({"tradingsymbol": self.symbol}, {"instrument_token": 1})
            instrumentTKN = result['instrument_token'] if result else None
            print(f"Instrument token for {self.symbol}:", instrumentTKN)

            # Connect Broker WebSocket
            kws = KiteTicker()
            logging.basicConfig(level=logging.DEBUG)

            def on_ticks(ws, ticks):
                # nonlocal currentLTP
                currentLTP = ticks[-1]['last_price']
                # if currentLTP < 100000:
                #     self.buy_stock(10, currentLTP)
                # else:
                #     print('Waiting')

            def on_connect(ws, response):
                ws.subscribe([int(instrumentTKN)])

            def on_close(ws, code, reason):
                ws.stop()

            kws.on_ticks = on_ticks
            kws.on_connect = on_connect
            kws.on_close = on_close

            kws.connect()

            current_price = currentLTP_list[-1]
            return current_price

    def calculate_profit_loss(self, current_price):
        if self.symbol in self.holdings:
            average_buy_price = self.holdings[self.symbol]['Invested'] / self.holdings[self.symbol]['Quantity']
            profit_loss = (current_price - average_buy_price) * self.holdings[self.symbol]['Quantity']
            return profit_loss
        else:
            return 0

    def average_buying_price(self):
        if self.symbol in self.holdings:
            return self.holdings[self.symbol]['Invested'] / self.holdings[self.symbol]['Quantity']
        else:
            return 0
