from apscheduler.schedulers.background import BackgroundScheduler
import import_elgoose
from sqlmodel import Session
from database import engine
import logging

logger = logging.getLogger(__name__)

scheduler = BackgroundScheduler()

def daily_import_job():
    logger.info("Starting daily Goose data import...")
    try:
        with Session(engine) as session:
            stats = import_elgoose.run_import(session, with_users=False)
            logger.info(f"Daily import complete. Stats: {stats}")
    except Exception as e:
        logger.error(f"Daily import failed: {e}")

from datetime import datetime, timedelta

def start_scheduler():
    # Regular interval
    scheduler.add_job(daily_import_job, 'interval', hours=12, id='goose_import')
    
    # Run once on startup (with 10s delay to let server settle)
    run_date = datetime.now() + timedelta(seconds=10)
    scheduler.add_job(daily_import_job, 'date', run_date=run_date, id='goose_import_startup')
    
    scheduler.start()
    logger.info("Scheduler started with daily import job.")
