from apscheduler.schedulers.asyncio import AsyncIOScheduler
from app.core.market_schedule import market_schedule
from app.services.kis_client import kis_client
from app.services.realtime_manager import realtime_manager
import logging

logger = logging.getLogger(__name__)

scheduler = AsyncIOScheduler()

async def market_check_job():
    """
    Periodic check to ensure Realtime Manager is connected when market is open.
    """
    is_domestic_open = market_schedule.is_market_open("Domestic")
    # is_overseas_open = market_schedule.is_market_open("Overseas")
    
    # If market is open and WS is not running, start it
    if is_domestic_open and not realtime_manager.running:
        logger.info("Market is Open! Starting Realtime Manager.")
        # This is a blocking call if awaited directly in job? NO, start() has a loop.
        # We should start it as a task if it's not running.
        # But realtime_manager.start() is a loop.
        # Better to have it managed by FastAPI startup, and this job just checks.
        pass

async def news_scrap_job():
    # Placeholder for News Scraper
    # logger.info("Scraping Naver News...")
    pass

async def auto_trade_scan_job():
    # Placeholder for Auto Trading Scanner (Check Reserved Orders)
    # logger.info("Scanning Reserved Orders...")
    pass

def start_scheduler():
    scheduler.add_job(market_check_job, 'interval', minutes=5)
    scheduler.add_job(news_scrap_job, 'interval', minutes=10)
    scheduler.add_job(auto_trade_scan_job, 'interval', minutes=1)
    
    scheduler.start()
    logger.info("Scheduler Started.")
