import logging
from datetime import timedelta
from app.extensions import db
from app.modules.hris.models import Holiday


class LeaveService:
    """
    Service for calculating leave duration and business logic.
    """

    # Keep policy explicit at service layer so routes and payroll stay consistent.
    LEAVE_POLICY_BY_SLUG = {
        'leave_type_unpaid': {
            'deduct_annual_balance': False,
            'deduct_salary': True
        }
    }

    @staticmethod
    def get_leave_policy(leave_type_status) -> dict:
        """
        Resolves leave policy from leave type status.

        Args:
            leave_type_status (Status | None): Leave type status record.

        Returns:
            dict: Policy flags for this leave type.
        """
        default_policy = {
            'deduct_annual_balance': True,
            'deduct_salary': False
        }

        if not leave_type_status:
            return default_policy

        policy = LeaveService.LEAVE_POLICY_BY_SLUG.get(getattr(leave_type_status, 'slug', ''), {})
        return {
            **default_policy,
            **policy
        }

    @staticmethod
    def should_deduct_annual_balance(leave_type_status) -> bool:
        """
        Determines whether this leave type should consume annual leave quota.

        Args:
            leave_type_status (Status | None): Leave type status record.

        Returns:
            bool: True if annual balance must be deducted.
        """
        return bool(LeaveService.get_leave_policy(leave_type_status)['deduct_annual_balance'])

    @staticmethod
    def should_deduct_salary(leave_type_status) -> bool:
        """
        Determines whether this leave type should reduce payroll amount.

        Args:
            leave_type_status (Status | None): Leave type status record.

        Returns:
            bool: True if payroll deduction applies.
        """
        return bool(LeaveService.get_leave_policy(leave_type_status)['deduct_salary'])

    @staticmethod
    def unpaid_leave_slugs() -> set[str]:
        """
        Returns all leave type slugs categorized as unpaid.

        Returns:
            set[str]: Slugs used for unpaid leave.
        """
        return {
            slug
            for slug, policy in LeaveService.LEAVE_POLICY_BY_SLUG.items()
            if policy.get('deduct_salary') is True
        }

    @staticmethod
    def calculate_duration(start_date, end_date, employee_id=None):
        """
        Calculates the number of business days between start and end date,
        excluding holidays. If employee_id is provided, it attempts to use 
        dynamic scheduling (EmployeeSchedule) to determine working days, 
        otherwise falls back to a standard Monday-Friday work week.

        Args:
            start_date (date): The start date of the leave.
            end_date (date): The end date of the leave.
            employee_id (str, optional): The ID of the employee to check specific schedules. Defaults to None.

        Returns:
            int: The total number of valid leave days deducted.
        """
        if end_date < start_date:
            return 0

        total_days = 0
        current_date = start_date

        # Pre-fetch holidays in range
        holidays = db.session.query(Holiday.date).filter(
            Holiday.date >= start_date,
            Holiday.date <= end_date
        ).all()
        holiday_dates = {h.date for h in holidays}

        # Pre-fetch dynamic schedules if employee_id is provided
        schedule_dates = set()
        if employee_id:
            from app.modules.hris.models.schedule import EmployeeSchedule
            schedules = db.session.query(EmployeeSchedule.date).filter(
                EmployeeSchedule.employee_id == employee_id,
                EmployeeSchedule.date >= start_date,
                EmployeeSchedule.date <= end_date
            ).all()
            schedule_dates = {s.date for s in schedules}

        while current_date <= end_date:
            is_holiday = current_date in holiday_dates
            
            is_working_day = False
            if employee_id and schedule_dates:
                # If specific schedules exist for this employee, a day is a working day if it's scheduled.
                is_working_day = current_date in schedule_dates
            else:
                # Fallback to standard Mon-Fri work week (0=Monday, 4=Friday)
                is_working_day = current_date.weekday() < 5

            if is_working_day and not is_holiday:
                total_days += 1

            current_date += timedelta(days=1)

        return total_days
