from providers.polygon import PolygonProvider

# Dictionary to store user watchlists
user_watchlists = {}

def add_to_watchlist(user_id, symbol):
    if user_id not in user_watchlists:
        user_watchlists[user_id] = set()  # Use a set to avoid duplicates
    user_watchlists[user_id].add(symbol)

def get_watchlist(user_id):
    return list(user_watchlists.get(user_id, []))

def remove_from_watchlist(user_id, symbol):
    if user_id in user_watchlists and symbol in user_watchlists[user_id]:
        user_watchlists[user_id].remove(symbol)

def calculate_watchlist_performance(watchlist):
    provider = PolygonProvider()
    performance = {}

    for symbol in watchlist:
        try:
            # Fetch latest price
            latest_price = provider.fetch_latest_price(symbol)

            # Fetch historical data (last 2 days) to calculate % change
            historical_data = provider.fetch_stock_data(symbol, interval="DAILY").tail(2)
            previous_close = historical_data['Close'].iloc[0]
            current_close = historical_data['Close'].iloc[-1]

            # Calculate percentage change
            percent_change = ((current_close - previous_close) / previous_close) * 100

            performance[symbol] = {
                "latest_price": latest_price,
                "percent_change": percent_change
            }
        except Exception as e:
            performance[symbol] = {"error": str(e)}

    return performance