from sqlalchemy.orm import Session
from app.db.database import SessionLocal, transaction
from app.services.external_api.tcgplayer.tcgplayer_inventory_service import TCGPlayerInventoryService
from app.services.file_processing_service import FileProcessingService
from app.services.scheduler.base_scheduler import BaseScheduler
import logging

logger = logging.getLogger(__name__)

class SchedulerService:
    def __init__(self):
        self.tcgplayer_service = TCGPlayerInventoryService()
        self.file_processor = FileProcessingService()
        self.scheduler = BaseScheduler()

    async def process_tcgplayer_export(self, export_type: str = "live", use_cache: bool = False):
        """
        Process TCGPlayer export as a scheduled task.
        
        Args:
            export_type: Type of export to process (staged, live, or pricing)
        """
        db = SessionLocal()
        try:
            logger.info(f"Starting scheduled TCGPlayer export processing for {export_type}")
            
            # Download the file
            file_bytes = await self.tcgplayer_service.get_tcgplayer_export(export_type)
            
            # Process the file and load into database
            with transaction(db):
                stats = await self.file_processor.process_tcgplayer_export(db, export_type=export_type, file_bytes=file_bytes, use_cache=use_cache)
            
            logger.info(f"Completed TCGPlayer export processing: {stats}")
            return stats
            
        except Exception as e:
            logger.error(f"Error processing TCGPlayer export: {str(e)}")
            raise
        finally:
            db.close()

    async def start_scheduled_tasks(self):
        """Start all scheduled tasks"""
        # Schedule TCGPlayer export processing to run daily at 2 AM
        await self.scheduler.schedule_task(
            task_name="process_tcgplayer_export",
            func=self.process_tcgplayer_export,
            interval_seconds=24 * 60 * 60,  # 24 hours
            export_type="live"
        )
        
        self.scheduler.start()
        logger.info("All scheduled tasks started") 