import logging
from datetime import time, datetime, timedelta
from app.extensions import db
from app.modules.hris.models import (
    Holiday, Attendance, Leave, Payslip, PayslipItem, SalaryComponent,
    Pph21TerRate, PtkpStatus, TerCategory, EmployeeSchedule
)
from app.core.models import Status
from app.modules.hris.services_leave import LeaveService


class PayrollService:
    """
    Handles Salary Calculations and Payslip Generation.
    Optimized for high-volume processing via bulk data fetching and 
    modularized for future Performance/KPI integration.
    """

    @staticmethod
    def get_setting(key: str, default_val: float = 0.0) -> float:
        """
        Retrieves a system configuration value from the Settings table.
        
        Args:
            key (str): The configuration key name.
            default_val (float): Value to return if key not found. Defaults to 0.0.
            
        Returns:
            float: The numeric value of the setting.
        """
        from app.core.models.settings import Settings
        setting = Settings.query.filter_by(key=key).first()
        if setting and setting.value:
            try:
                return float(setting.value)
            except ValueError:
                pass
        return float(default_val)

    @staticmethod
    def calculate_attendance_stats(employee, start_date, end_date, pre_fetched_attendance=None, pre_fetched_leaves=None):
        """
        Calculates attendance and leave-derived metrics for a specific employee 
        within a given payroll period. Supports bulk data to avoid N+1 query overhead.

        Args:
            employee (Employee): Employee model instance.
            start_date (date): Start of the evaluation period.
            end_date (date): End of the evaluation period.
            pre_fetched_attendance (list, optional): List of relevant attendance records.
            pre_fetched_leaves (list, optional): List of relevant approved leave records.

        Returns:
            dict: Summary of days worked, working days, leave days, absences, overtime, and lateness.
        """
        if pre_fetched_attendance is not None:
            attendances = [a for a in pre_fetched_attendance if a.date >= start_date and a.date <= end_date]
        else:
            attendances = Attendance.query.filter(
                Attendance.employee_id == employee.id,
                Attendance.date >= start_date,
                Attendance.date <= end_date
            ).all()

        days_worked = len(attendances)
        overtime_hours = 0
        late_minutes = 0
        late_days = 0

        # Optimization: Use employee's shift start time or default to 09:00
        shift_start_time = employee.shift.start_time if (employee.shift and employee.shift.start_time) else time(9, 0)
        
        # 15 minutes tolerance typically allowed before being marked 'late'
        late_threshold = time(shift_start_time.hour, shift_start_time.minute + 15) if shift_start_time.minute < 45 else time(shift_start_time.hour + 1, shift_start_time.minute - 45)

        for attn in attendances:
            is_late_today = False
            if attn.check_in and attn.check_in.time() > late_threshold:
                late_delta = datetime.combine(attn.date, attn.check_in.time()) - datetime.combine(attn.date, shift_start_time)
                late_minutes += int(late_delta.total_seconds() / 60)
                is_late_today = True
                
            if is_late_today:
                late_days += 1
                
            if attn.check_out and attn.check_in:
                duration = attn.check_out - attn.check_in
                # Standard threshold for overtime (standard 8 work hours + 1 break hour)
                if duration.total_seconds() > 9 * 3600:
                    overtime_hours += int((duration.total_seconds() - (9 * 3600)) / 3600)

        working_days = PayrollService.calculate_working_days(start_date, end_date, employee_id=employee.id)
        paid_leave_days, unpaid_leave_days = PayrollService.calculate_approved_leave_days(
            employee, start_date, end_date, pre_fetched_leaves=pre_fetched_leaves
        )

        compensated_days = days_worked + paid_leave_days + unpaid_leave_days
        unexcused_absence_days = max(0, working_days - compensated_days)

        return {
            'days_worked': days_worked,
            'working_days': working_days,
            'paid_leave_days': paid_leave_days,
            'unpaid_leave_days': unpaid_leave_days,
            'unexcused_absence_days': unexcused_absence_days,
            'overtime_hours': overtime_hours,
            'late_minutes': late_minutes,
            'late_days': late_days
        }

    @staticmethod
    def calculate_working_days(start_date, end_date, holiday_dates=None, employee_id=None):
        """
        Determines the total number of expected working days in a period.
        Prioritizes specific employee shift schedules if available.

        Args:
            start_date (date): Period start.
            end_date (date): Period end.
            holiday_dates (set, optional): Set of date objects representing holidays.
            employee_id (str, optional): Target employee for dynamic schedule lookup.

        Returns:
            int: Count of working days.
        """
        if end_date < start_date:
            return 0

        if holiday_dates is None:
            holidays = db.session.query(Holiday.date).filter(
                Holiday.date >= start_date,
                Holiday.date <= end_date
            ).all()
            holiday_dates = {h.date for h in holidays}

        schedule_dates = set()
        if employee_id:
            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}

        total_days = 0
        current_date = start_date
        while current_date <= end_date:
            is_holiday = current_date in holiday_dates
            
            is_working_day = False
            if employee_id and schedule_dates:
                is_working_day = current_date in schedule_dates
            else:
                # Default work week fallback
                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

    @staticmethod
    def calculate_approved_leave_days(employee, start_date, end_date, pre_fetched_leaves=None):
        """
        Sums up the approved leave duration within a payroll window, 
        differentiating between paid and unpaid leaves.

        Args:
            employee (Employee): Target employee.
            start_date (date): Evaluation start.
            end_date (date): Evaluation end.
            pre_fetched_leaves (list, optional): Bulk data for performance.

        Returns:
            tuple: (int: paid_leave_days, int: unpaid_leave_days).
        """
        if pre_fetched_leaves is not None:
            leaves = [l for l in pre_fetched_leaves if l.start_date <= end_date and l.end_date >= start_date]
        else:
            approved_status = Status.query.filter_by(module='hris', slug='leave_approved').first()
            if not approved_status:
                return 0, 0

            leaves = Leave.query.options(db.joinedload(Leave.leave_type)).filter(
                Leave.employee_id == employee.id,
                Leave.status_id == approved_status.id,
                Leave.start_date <= end_date,
                Leave.end_date >= start_date
            ).all()

        paid_leave_days = 0
        unpaid_leave_days = 0

        for leave in leaves:
            overlap_start = max(leave.start_date, start_date)
            overlap_end = min(leave.end_date, end_date)
            leave_days = LeaveService.calculate_duration(overlap_start, overlap_end, employee_id=employee.id)

            if leave_days <= 0:
                continue

            if LeaveService.should_deduct_salary(leave.leave_type):
                unpaid_leave_days += leave_days
            else:
                paid_leave_days += leave_days

        return paid_leave_days, unpaid_leave_days

    @staticmethod
    def normalize_ptkp_status(ptkp_status: str | None) -> str:
        """
        Normalizes various PTKP status inputs into canonical Indonesian tax notation (e.g., TK/0, K/I/1).
        
        Args:
            ptkp_status (str, optional): Raw input from employee profile.
            
        Returns:
            str: Normalized canonical string.
        """
        if not ptkp_status: return 'TK/0'
        raw = str(ptkp_status).strip().upper()
        if not raw: return 'TK/0'
        aliases = {
            'TK0': 'TK/0', 'TK1': 'TK/1', 'TK2': 'TK/2', 'TK3': 'TK/3',
            'K0': 'K/0', 'K1': 'K/1', 'K2': 'K/2', 'K3': 'K/3',
            'KI0': 'K/I/0', 'KI1': 'K/I/1', 'KI2': 'K/I/2', 'KI3': 'K/I/3'
        }
        if raw in aliases: return aliases[raw]
        compact = raw.replace('/', '')
        if compact in aliases: return aliases[compact]
        return raw

    @staticmethod
    def determine_ter_category(ptkp_status: str) -> TerCategory:
        """
        Maps PTKP status to Indonesian TER (Tarif Efektif Rata-rata) Categories (A, B, or C).
        Falls back to Category A (TK/0) with a warning if the PTKP status is unrecognized.
        
        Args:
            ptkp_status (str): Normalized PTKP status.
            
        Returns:
            TerCategory: The mapped category enum.
        """
        normalized = PayrollService.normalize_ptkp_status(ptkp_status)
        if normalized in ['TK/0', 'TK/1', 'K/0']: return TerCategory.A
        elif normalized in ['TK/2', 'TK/3', 'K/1', 'K/2']: return TerCategory.B
        elif normalized in ['K/3', 'K/I/0', 'K/I/1', 'K/I/2', 'K/I/3']: return TerCategory.C
        
        return TerCategory.A

    @staticmethod
    def find_ter_rate(total_gross: float, ptkp_status: str) -> Pph21TerRate:
        """
        Locates the specific PPh21 TER rate based on gross income and PTKP status.
        
        Args:
            total_gross (float): Total taxable gross income for the period.
            ptkp_status (str): Normalized PTKP status.
            
        Returns:
            Pph21TerRate: Matching rate object from DB.
        """
        cat = PayrollService.determine_ter_category(ptkp_status)
        return Pph21TerRate.query.filter(
            Pph21TerRate.category == cat,
            Pph21TerRate.gross_income_min <= total_gross,
            Pph21TerRate.gross_income_max >= total_gross
        ).order_by(Pph21TerRate.gross_income_min.desc()).first()

    @staticmethod
    def calculate_pph21_ter(total_gross: float, ptkp_status: str) -> float:
        """
        Calculates monthly PPh21 tax using the TER method.
        
        Args:
            total_gross (float): Period gross income.
            ptkp_status (str): PTKP status string.
            
        Returns:
            float: Calculated tax amount.
        """
        rate_obj = PayrollService.find_ter_rate(total_gross, ptkp_status)
        if rate_obj:
            return float(total_gross * float(rate_obj.rate_percent) / 100.0)
        return 0.0

    @staticmethod
    def generate_payslip(
        employee, start_date, end_date, run_type: str = 'default',
        source_batch_id: str | None = None, reference_start=None, reference_end=None,
        pre_fetched_data=None
    ):
        """
        Core logic for generating a draft payslip object. 
        Calculates base salary, allowances, deductions, unpaid leave penalties, and PPh21 tax.
        
        Uses pre_fetched_data map to avoid massive database hits during batch runs.
        """
        attn_list = pre_fetched_data.get('attendance', {}).get(employee.id) if pre_fetched_data else None
        leave_list = pre_fetched_data.get('leaves', {}).get(employee.id) if pre_fetched_data else None
        holiday_dates = pre_fetched_data.get('holiday_dates') if pre_fetched_data else None
        components = pre_fetched_data.get('components') if pre_fetched_data else SalaryComponent.query.filter_by(deleted_at=None).all()

        stats = PayrollService.calculate_attendance_stats(
            employee, start_date, end_date, 
            pre_fetched_attendance=attn_list, pre_fetched_leaves=leave_list
        )
        
        period_start = reference_start or start_date
        period_end = reference_end or end_date

        if (employee.join_date and employee.join_date > end_date) or not employee.base_salary or employee.base_salary <= 0:
            return None, []

        absence_days = stats['unexcused_absence_days']
        gross_income = 0.0; base_notes = ""

        # 1. Base Earnings Proration
        if employee.salary_type == 'monthly':
            ref_working_days = max(1, PayrollService.calculate_working_days(period_start, period_end, holiday_dates=holiday_dates, employee_id=employee.id))
            seg_working_days = max(0, stats['working_days'])
            gross_income = (employee.base_salary * seg_working_days) / ref_working_days
            base_notes = "Monthly Base Salary" if (start_date == period_start and end_date == period_end) else f"Prorated Monthly Salary ({seg_working_days}/{ref_working_days} working days)"
        elif employee.salary_type == 'daily':
            payable_days = stats['days_worked'] + stats['paid_leave_days']
            gross_income = employee.base_salary * payable_days
            base_notes = f"Daily Salary ({payable_days} paid days @ Rp {employee.base_salary:,.2f})"

        allowances = 0.0; deductions = 0.0; items = []
        items.append(PayslipItem(name='Base Salary', type='earning', amount=gross_income, source_notes=base_notes))

        company_bpjs_rate = PayrollService.get_setting('company_bpjs_rate', default_val=0.0)
        
        # 2. Process Salary Components (Earnings)
        for comp in components:
            if comp.type != 'earning': continue
            amount = 0.0; notes = ""
            if comp.calculation_type == 'fixed_amount':
                amount = comp.default_amount; notes = "Standard Fixed"
            elif comp.calculation_type == 'percentage_gross':
                val = company_bpjs_rate if ('bpjs' in comp.name.lower() and 'perusahaan' in comp.name.lower() and company_bpjs_rate > 0) else comp.default_amount
                amount = (gross_income * val) / 100
                notes = f"({val}% of Base Rp {gross_income:,.2f})"
            elif comp.calculation_type == 'per_occurrence':
                occ = stats['days_worked'] if ('meal' in comp.name.lower() or 'transport' in comp.name.lower() or 'makan' in comp.name.lower()) else (stats['overtime_hours'] if ('overtime' in comp.name.lower() or 'lembur' in comp.name.lower()) else 0)
                amount = comp.default_amount * occ
                notes = f"({occ} occurrences x Rp {comp.default_amount:,.2f})"

            if amount > 0:
                allowances += amount
                items.append(PayslipItem(name=comp.name, type='earning', amount=amount, component_id=comp.id, source_notes=notes))

        # --- PERFORMANCE / KPI INTEGRATION (TODO) ---
        # integration placeholder removed logic for random seeds
        total_gross_for_tax = gross_income + allowances

        # 3. Unpaid Leave Penalties
        if employee.salary_type == 'monthly' and stats['unpaid_leave_days'] > 0:
            ref_working_days = max(1, PayrollService.calculate_working_days(period_start, period_end, holiday_dates=holiday_dates, employee_id=employee.id))
            daily_rate = employee.base_salary / ref_working_days
            unpaid_deduction = daily_rate * stats['unpaid_leave_days']
            deductions += unpaid_deduction
            items.append(PayslipItem(
                name='Unpaid Leave Deduction', type='deduction', amount=unpaid_deduction,
                source_notes=f"{stats['unpaid_leave_days']} unpaid day(s) x Rp {daily_rate:,.2f}",
                is_system_generated=True, system_key='unpaid_leave_deduction', is_override_locked=True
            ))

        # 4. Process Salary Components (Deductions)
        for comp in components:
            if comp.type != 'deduction' or 'pph 21' in comp.name.lower(): continue
            amount = 0.0; notes = ""
            if comp.calculation_type == 'fixed_amount':
                amount = comp.default_amount; notes = "Standard Fixed"
            elif comp.calculation_type == 'percentage_gross':
                val = company_bpjs_rate if ('bpjs' in comp.name.lower() and 'non-tunai' in comp.name.lower() and company_bpjs_rate > 0) else comp.default_amount
                amount = (gross_income * val) / 100
                notes = f"({val}% of Base Rp {gross_income:,.2f})"
            elif comp.calculation_type == 'per_occurrence':
                occ = stats['late_days'] if ('late' in comp.name.lower() or 'lambat' in comp.name.lower()) else (absence_days if ('absent' in comp.name.lower() or 'alpha' in comp.name.lower()) else 0)
                amount = comp.default_amount * occ
                notes = f"({occ} occurrences x Rp {comp.default_amount:,.2f})"

            if amount > 0:
                deductions += amount
                items.append(PayslipItem(name=comp.name, type='deduction', amount=amount, component_id=comp.id, source_notes=notes))

        # 5. Tax Calculation (TER Method)
        normalized_ptkp = PayrollService.normalize_ptkp_status(employee.ptkp_status)
        valid_ptkp_values = [e.value for e in PtkpStatus]
        ptkp_is_valid = normalized_ptkp in valid_ptkp_values
        
        tax_rate_obj = PayrollService.find_ter_rate(total_gross_for_tax, normalized_ptkp)
        tax_amount = 0.0
        
        ptkp_warning = "" if ptkp_is_valid else f" [WARNING: PTKP '{employee.ptkp_status}' invalid, defaulted to TK/0]"
        tax_notes = f"Nil: TER {normalized_ptkp} not found for Gross Rp {total_gross_for_tax:,.2f}{ptkp_warning}"
        
        if tax_rate_obj:
            tax_rate = float(tax_rate_obj.rate_percent)
            tax_amount = float(total_gross_for_tax * tax_rate / 100.0)
            tax_notes = f"TER Category {tax_rate_obj.category.value} ({normalized_ptkp}) {tax_rate:.3f}% on Gross Rp {total_gross_for_tax:,.2f}{ptkp_warning}"

        deductions += tax_amount
        items.append(PayslipItem(name='PPh21', type='deduction', amount=tax_amount, source_notes=tax_notes))

        # Final Aggregation
        net_salary = total_gross_for_tax - deductions
        status_draft = Status.query.filter_by(module='hris', slug='payslip_draft').first()

        payslip = Payslip(
            employee_id=employee.id, period_start=period_start, period_end=period_end,
            covered_start_date=start_date, covered_end_date=end_date, run_type=run_type,
            source_batch_id=source_batch_id, base_salary=gross_income, total_allowances=allowances,
            total_deductions=deductions, pph21_amount=tax_amount, net_salary=net_salary,
            status_id=status_draft.id if status_draft else None,
            attendance_days=stats['days_worked'], absence_days=absence_days,
            overtime_hours=stats['overtime_hours'], late_minutes=stats['late_minutes']
        )

        return payslip, items

    @staticmethod
    def get_existing_coverages(employee_id: str, start_date, end_date) -> list:
        """
        Retrieves existing payslip coverage windows for an employee to prevent double payment.
        """
        overlaps = Payslip.query.filter(Payslip.employee_id == employee_id, Payslip.covered_start_date <= end_date, Payslip.covered_end_date >= start_date).all()
        return [(max(p.covered_start_date, start_date), min(p.covered_end_date, end_date), p.id) for p in overlaps]

    @staticmethod
    def merge_intervals(intervals: list) -> list:
        """
        Standard interval merging algorithm.
        """
        if not intervals: return []
        sorted_it = sorted(intervals, key=lambda x: x[0])
        merged = [sorted_it[0]]
        for curr_s, curr_e in sorted_it[1:]:
            last_s, last_e = merged[-1]
            if curr_s <= (last_e + timedelta(days=1)): merged[-1] = (last_s, max(last_e, curr_e))
            else: merged.append((curr_s, curr_e))
        return merged

    @staticmethod
    def subtract_intervals(target_start, target_end, covered_intervals: list) -> list:
        """
        Subtracts covered periods from a target date range to find unpaid segments.
        """
        uncovered = []; cursor = target_start
        for cov_s, cov_e in covered_intervals:
            if cov_e < cursor: continue
            if cov_s > target_end: break
            if cov_s > cursor: uncovered.append((cursor, min(cov_s - timedelta(days=1), target_end)))
            cursor = max(cursor, cov_e + timedelta(days=1))
            if cursor > target_end: break
        if cursor <= target_end: uncovered.append((cursor, target_end))
        return uncovered

    @staticmethod
    def calculate_uncovered_intervals(employee_id: str, start_date, end_date):
        """
        Finds gaps in payroll coverage for a given period and employee.
        """
        coverages = PayrollService.get_existing_coverages(employee_id, start_date, end_date)
        merged = PayrollService.merge_intervals([(c[0], c[1]) for c in coverages])
        return PayrollService.subtract_intervals(start_date, end_date, merged), [c[2] for c in coverages]
