from app.db.database import transaction
from app.services.scheduler.base_scheduler import BaseScheduler
import logging

logger = logging.getLogger(__name__)

class SchedulerService:
    def __init__(self):
        self.scheduler = BaseScheduler()
        # Service manager will be set during initialization
        self._service_manager = None

    @property
    def service_manager(self):
        if self._service_manager is None:
            from app.services.service_manager import ServiceManager
            self._service_manager = ServiceManager()
        return self._service_manager
    
    async def update_open_orders_hourly(self, db):
        """
        Hourly update of orders from TCGPlayer API to database
        """
        try:
            logger.info("Starting hourly order update")
            # Get order management service
            order_management = self.service_manager.get_service('order_management')
            
            # get all open orders from last 7 days
            orders = await order_management.get_order_ids(open_only=True, search_range="LastWeek")
            for order_id in orders:
                order = await order_management.get_order(order_id)
                with transaction(db):
                    await order_management.save_order_to_db(order, db)
            
            logger.info("Completed hourly order update")
            
        except Exception as e:
            logger.error(f"Error updating open orders: {str(e)}")
            raise
            
    async def update_all_orders_daily(self, db):
        """
        Daily update of all orders from TCGPlayer API to database
        """
        try:
            logger.info("Starting daily order update")
            # Get order management service
            order_management = self.service_manager.get_service('order_management')
            
            # get all order ids from last 3 months
            orders = await order_management.get_order_ids(open_only=False, search_range="LastThreeMonths")
            for order_id in orders:
                order = await order_management.get_order(order_id)
                with transaction(db):
                    await order_management.save_order_to_db(order, db)
            
            logger.info("Completed daily order update")

        except Exception as e:
            logger.error(f"Error updating all orders: {str(e)}")
            raise
            
    async def start_scheduled_tasks(self, db):
        """Start all scheduled tasks"""
        # Schedule open orders update to run hourly at 00 minutes
        await self.scheduler.schedule_task(
            task_name="update_open_orders_hourly",
            func=lambda: self.update_open_orders_hourly(db),
            interval_seconds=60 * 60,  # 1 hour
        )
        # Schedule all orders update to run daily at 1 AM
        await self.scheduler.schedule_task(
            task_name="update_all_orders_daily",
            func=lambda: self.update_all_orders_daily(db),
            interval_seconds=24 * 60 * 60,  # 24 hours
        )
        
        self.scheduler.start()
        logger.info("All scheduled tasks started")

    async def close(self):
        """Close all services used by the scheduler"""
        try:
            await self.scheduler.shutdown()
            logger.info("Scheduler services closed")
        except Exception as e:
            logger.error(f"Error closing scheduler services: {str(e)}")
            raise 