from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from .database import SessionLocal
from .db_manager import DbManager
from . import models
import logging

log = logging.getLogger("ainventory")
scheduler = BackgroundScheduler()

def scheduled_backup_job():
    """System triggered automated backup."""
    db = SessionLocal()
    try:
        log.info("[SCHEDULER] Starting automated backup job...")
        DbManager.create_backup(db, label="auto", user_id=None)
    except Exception as e:
        log.error(f"[SCHEDULER] Automated backup failed: {str(e)}")
    finally:
        db.close()

def sync_scheduler_config():
    """Read DB settings and update the scheduler job."""
    db = SessionLocal()
    try:
        hour_s = db.query(models.SystemSetting).filter(models.SystemSetting.key == "backup_schedule_hour").first()
        freq_s = db.query(models.SystemSetting).filter(models.SystemSetting.key == "backup_schedule_freq_days").first()
        
        hour = int(hour_s.value) if hour_s else 3
        freq = int(freq_s.value) if freq_s else 1
        
        # Remove existing backup jobs to avoid duplicates
        for job in scheduler.get_jobs():
            if job.id == "auto_backup":
                scheduler.remove_job(job.id)
        
        # Add job with cron trigger: trigger at 'hour' every 'freq' days
        # Use day='*/freq' for intervals in days
        trigger = CronTrigger(hour=hour, minute=0, day=f"*/{freq}")
        scheduler.add_job(scheduled_backup_job, trigger, id="auto_backup")
        
        log.info(f"[SCHEDULER] Policy synced: Every {freq} days at {hour:02d}:00")
    except Exception as e:
        log.error(f"[SCHEDULER] Failed to sync config: {str(e)}")
    finally:
        db.close()
