"""
Staff Shift Automation Scheduler
Background scheduler for automatic shift status management
"""

import threading
import time
from datetime import datetime, timedelta
from typing import Optional
from sqlalchemy.orm import Session

from ...shared.config.database import get_db
from ...shared.config.logging_config import get_logger
from .shift_automation_service import shift_automation_service

logger = get_logger(__name__)


class ShiftScheduler:
    """Background scheduler for automatic shift status updates"""
    
    def __init__(self):
        self.running = False
        self.thread: Optional[threading.Thread] = None
        self.check_interval_seconds = 60  # Check every minute
        self.last_run_time: Optional[datetime] = None
    
    def start(self):
        """Start the background shift scheduler"""
        if self.running:
            logger.warning("Shift Scheduler is already running")
            return
        
        self.running = True
        self.thread = threading.Thread(target=self._scheduler_loop, daemon=True)
        self.thread.start()
        logger.info("Shift Scheduler started - automatic shift management enabled")
    
    def stop(self):
        """Stop the background shift scheduler"""
        if not self.running:
            return
        
        self.running = False
        if self.thread:
            self.thread.join(timeout=5.0)
        logger.info("Shift Scheduler stopped")
    
    def _scheduler_loop(self):
        """Main scheduler loop that runs shift automation periodically"""
        logger.info("Shift Scheduler loop started")
        
        # Wait a bit for the app to fully start
        time.sleep(10)
        
        while self.running:
            try:
                current_time = datetime.utcnow()
                
                # Run shift automation
                logger.debug("Running scheduled shift automation check...")
                stats = self._run_shift_automation()
                
                self.last_run_time = current_time
                
                # Log summary if there were changes
                if any([
                    stats.get("auto_started", 0) > 0,
                    stats.get("auto_completed", 0) > 0,
                    stats.get("marked_no_show", 0) > 0
                ]):
                    logger.info(
                        f"Shift automation run completed: "
                        f"{stats.get('auto_started', 0)} started, "
                        f"{stats.get('auto_completed', 0)} completed, "
                        f"{stats.get('marked_no_show', 0)} no-shows"
                    )
                
                # Sleep until next check
                time.sleep(self.check_interval_seconds)
                
            except Exception as e:
                logger.error(f"Error in shift scheduler loop: {str(e)}", exc_info=True)
                # Sleep for 30 seconds before retrying on error
                time.sleep(30)
    
    def _run_shift_automation(self) -> dict:
        """Run shift automation process with database session management"""
        db_gen = get_db()
        db = next(db_gen)
        
        try:
            stats = shift_automation_service.process_shift_automation(db)
            return stats
        except Exception as e:
            logger.error(f"Error running shift automation: {str(e)}", exc_info=True)
            return {"processed": 0, "auto_started": 0, "auto_completed": 0, "marked_no_show": 0, "errors": 1}
        finally:
            db.close()
    
    def get_status(self) -> dict:
        """Get scheduler status information"""
        return {
            "running": self.running,
            "last_run_time": self.last_run_time.isoformat() if self.last_run_time else None,
            "check_interval_seconds": self.check_interval_seconds
        }


# Singleton instance
_shift_scheduler: Optional[ShiftScheduler] = None


def get_shift_scheduler() -> ShiftScheduler:
    """Get or create the singleton shift scheduler instance"""
    global _shift_scheduler
    if _shift_scheduler is None:
        _shift_scheduler = ShiftScheduler()
    return _shift_scheduler

