import time
from datetime import datetime, date
from logging_config import get_logger

logger = get_logger(__name__)

class Scheduler:
    def __init__(self, processor, config):
        self.processor = processor
        self.config = config

        # Cycle tracking
        self.last_cycle_date = None
        self.cycle_no = 0

    def _update_cycle(self):
        today = date.today()

        if self.last_cycle_date != today:
            # New day → reset cycle
            self.cycle_no = 1
            self.last_cycle_date = today
        else:
            # Same day → increment
            self.cycle_no += 1

    def run(self):
        logger.info("NEFT OUTWARD Scheduler started")

        while True:
            try:
                self._update_cycle()

                now = datetime.now()

                logger.info(
                    "=== Starting processing cycle %s | Date: %s | Time: %s ===",
                    self.cycle_no,
                    now.strftime("%Y-%m-%d"),
                    now.strftime("%H:%M:%S")
                )

                self.processor.process()

                end_time = datetime.now()

                logger.info(
                    "=== Completed processing cycle %s | Date: %s | Time: %s ===",
                    self.cycle_no,
                    end_time.strftime("%Y-%m-%d"),
                    end_time.strftime("%H:%M:%S")
                )

            except Exception:
                logger.exception(
                    "Error occurred during cycle %s on %s",
                    self.cycle_no,
                    self.last_cycle_date
                )

            logger.info(
                "Scheduler sleeping for %s minutes",
                self.config.poll_interval_minutes
            )

            time.sleep(self.config.poll_interval_minutes * 60)

