from apscheduler.schedulers.asyncio import AsyncIOScheduler
from telegram.ext import Application, CommandHandler
from telegram_service.handlers import (
	start, 
  analyze,
  setprovider,
  news, 
  dividends, 
  options, 
  portfolio, 
  earnings, 
	compare, 
	sector, 
	risk, 
	watchlist, 
	screener,
	learn,
	help
)
from config.settings import TELEGRAM_BOT_TOKEN
from telegram.ext import Application, CommandHandler
from stocks.watchlist import calculate_watchlist_performance, user_watchlists

def send_daily_watchlist_updates(application):
    async def send_updates():
        for user_id, watchlist in user_watchlists.items():
            if not watchlist:
                continue

            try:
                performance = calculate_watchlist_performance(watchlist)

                message = "Daily Watchlist Update:\n\n"
                for symbol, data in performance.items():
                    if "error" in data:
                        message += f"- {symbol}: Error fetching data ({data['error']})\n"
                    else:
                        message += (
                            f"- {symbol}: "
                            f"Latest Price: ${data['latest_price']:.2f}, "
                            f"% Change: {data['percent_change']:.2f}%\n"
                        )

                await application.bot.send_message(chat_id=user_id, text=message)

            except Exception as e:
                print(f"Error sending watchlist update to user {user_id}: {str(e)}")

    scheduler = AsyncIOScheduler()
    scheduler.add_job(send_updates, "cron", hour=9, minute=0)  # Send updates daily at 9 AM
    scheduler.start()
    
def run_bot():
    application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help))
    application.add_handler(CommandHandler("analyze", analyze))
    application.add_handler(CommandHandler("setprovider", setprovider))
    application.add_handler(CommandHandler("news", news))
    application.add_handler(CommandHandler("dividends", dividends))
    application.add_handler(CommandHandler("options", options))
    application.add_handler(CommandHandler("portfolio", portfolio))
    application.add_handler(CommandHandler("earnings", earnings))
    application.add_handler(CommandHandler("compare", compare))
    application.add_handler(CommandHandler("sector", sector))
    application.add_handler(CommandHandler("risk", risk))
    application.add_handler(CommandHandler("watchlist", watchlist))
    application.add_handler(CommandHandler("screener", screener))
    application.add_handler(CommandHandler("learn", learn))
    
		# Start the scheduler
    # send_daily_watchlist_updates(application)
    
    application.run_polling()