# main.py
from fastapi import FastAPI, HTTPException
from pymongo import MongoClient
import logging
from zerodha.zerodha_ticker import KiteTicker
from portfolioObj import Portfolio
from datetime import date, datetime

app = FastAPI()

# MongoDB Connection
# client = MongoClient("mongodb://192.168.31.176:27017/")
# database = client["zerodha_test"]

client = MongoClient("mongodb://jenya:DJenya$Mongo%40St0ckDB@172.105.59.175:27017/")
database = client["trade_iq"]
collection = database["zerodha_instruments"]
creds_collection = database["zerodha_credentials"]
today = date.today()

# Fetch credentials
enctoken_obj = creds_collection.find_one({"date": str(today)}, {"_id": 0, "enctoken": 1})
websocket_obj = creds_collection.find_one({"date": str(today)}, {"_id": 0, "websocket": 1})
websocket = websocket_obj["websocket"]
#ticker = KiteTicker(socket_url=websocket)

# Zerodha Ticker WebSocket setup (Placeholder setup)
kws = KiteTicker(socket_url=websocket)
logging.basicConfig(level=logging.DEBUG)


# main.py continued
from models import Trade, PortfolioData
from fastapi import Body

@app.post("/portfolio/buy")
async def buy_stock(trade: Trade = Body(...)):
    portfolio = Portfolio(trade.symbol)
    portfolio.buy_stock(trade.quantity, trade.price)
    # Store the updated holdings and investment details in MongoDB
    collection.update_one(
        {"_id": portfolio.symbol},
        {"$set": portfolio.__dict__},
        upsert=True
    )
    return {"status": "Bought", "data": portfolio.__dict__}

@app.post("/portfolio/sell")
async def sell_stock(trade: Trade = Body(...)):
    portfolio = Portfolio(trade.symbol)
    portfolio.sell_stock(trade.quantity, trade.price)
    # Update the portfolio in MongoDB
    collection.update_one(
        {"_id": portfolio.symbol},
        {"$set": portfolio.__dict__},
        upsert=True
    )
    return {"status": "Sold", "data": portfolio.__dict__}


@app.get("/portfolio/value")
async def portfolio_value():
    portfolio = Portfolio("")  # Replace with relevant symbol(s) if needed
    value = portfolio.portfolio_value()
    return {"total_portfolio_value": value}


from fastapi.websockets import WebSocket

@app.websocket("/ws/prices/{symbol}")
async def websocket_endpoint(websocket: WebSocket, symbol: str):
    await websocket.accept()
    instrument_token = collection.find_one({"tradingsymbol": symbol})["instrument_token"]

    def on_ticks(ws, ticks):
        current_price = ticks[-1]['last_price']
        websocket.send_json({"symbol": symbol, "price": current_price})   # type: ignore

    kws.on_ticks = on_ticks
    kws.connect()
    
    # Keep WebSocket connection alive
    while True:
        await websocket.receive_text()  # Placeholder for continuous connection
