"""
Automatic backup scheduler
Runs database backups on a schedule without needing cron
"""
import os
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from backup_restore_api import perform_backup
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

scheduler = BackgroundScheduler()


def scheduled_backup_job():
    """Job that runs on schedule to perform backup"""
    logger.info("Starting scheduled backup...")
    try:
        result = perform_backup()
        if result['success']:
            logger.info(f"✅ Scheduled backup completed: {result['filename']}")
        else:
            logger.error(f"❌ Scheduled backup failed: {result.get('error', 'Unknown error')}")
    except Exception as e:
        logger.error(f"❌ Scheduled backup exception: {str(e)}")


def start_backup_scheduler():
    """Start the backup scheduler based on environment configuration"""
    
    # Get backup interval from environment (default: weekly)
    backup_interval = os.getenv('BACKUP_INTERVAL', 'weekly').lower()
    
    if backup_interval == 'disabled':
        logger.info("⏸️  Automatic backups are DISABLED")
        return
    
    if backup_interval == 'test' or backup_interval == '1minute':
        # Test mode - every 1 minute
        scheduler.add_job(
            scheduled_backup_job,
            'interval',
            minutes=1,
            id='backup_job',
            replace_existing=True
        )
        logger.info("⏰ Backup scheduler started: EVERY 1 MINUTE (testing mode)")
        logger.warning("⚠️  WARNING: Test mode active! Change BACKUP_INTERVAL to 'weekly' for production")
        
    elif backup_interval == 'daily':
        # Daily at 2 AM
        scheduler.add_job(
            scheduled_backup_job,
            'cron',
            hour=2,
            minute=0,
            id='backup_job',
            replace_existing=True
        )
        logger.info("⏰ Backup scheduler started: DAILY at 2:00 AM")
        
    elif backup_interval == 'weekly':
        # Weekly - Sunday at 2 AM
        scheduler.add_job(
            scheduled_backup_job,
            'cron',
            day_of_week='sun',
            hour=2,
            minute=0,
            id='backup_job',
            replace_existing=True
        )
        logger.info("⏰ Backup scheduler started: WEEKLY on Sundays at 2:00 AM")
        
    else:
        logger.warning(f"⚠️  Unknown BACKUP_INTERVAL: {backup_interval}, defaulting to weekly")
        scheduler.add_job(
            scheduled_backup_job,
            'cron',
            day_of_week='sun',
            hour=2,
            minute=0,
            id='backup_job',
            replace_existing=True
        )
        logger.info("⏰ Backup scheduler started: WEEKLY on Sundays at 2:00 AM")
    
    scheduler.start()
    logger.info("✅ Backup scheduler is running")


def stop_backup_scheduler():
    """Stop the backup scheduler"""
    if scheduler.running:
        scheduler.shutdown()
        logger.info("🛑 Backup scheduler stopped")
