from app.db.database import transaction
from app.services.scheduler.base_scheduler import BaseScheduler
from app.services.base_service import BaseService
from sqlalchemy import text
import logging

logger = logging.getLogger(__name__)

class SchedulerService(BaseService):
    def __init__(self):
        # Initialize BaseService with None as model since this service doesn't have a specific model
        super().__init__(None)
        self.scheduler = BaseScheduler()

    async def update_tcgplayer_price_history_daily(self, db):
        """
        Update the TCGPlayer price history table
        """
        with transaction(db):
            await db.execute(text("""REFRESH MATERIALIZED VIEW CONCURRENTLY most_recent_tcgplayer_price;"""))
            logger.info("TCGPlayer price history refreshed")
    
    
    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),
            cron_expression="0 * * * *"  # Run at minute 0 of every hour
        )
        # Schedule all orders update to run daily at 3 AM
        await self.scheduler.schedule_task(
            task_name="update_all_orders_daily",
            func=lambda: self.update_all_orders_daily(db),
            cron_expression="0 3 * * *"  # Run at 3:00 AM every day
        )
        # Schedule TCGPlayer price history update to run daily at 1 AM
        await self.scheduler.schedule_task(
            task_name="update_tcgplayer_price_history_daily",
            func=lambda: self.update_tcgplayer_price_history_daily(db),
            cron_expression="0 1 * * *"  # Run at 1:00 AM every day
        )
        
        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 