from decimal import Decimal, ROUND_HALF_UP
from .models import PayrollStatutoryRuleSet


class NepalPayrollEngine:
    """Computes statutory PF, SSF, and progressive income tax strictly from effective-dated rules."""

    @staticmethod
    def get_active_ruleset(company, as_of_date) -> PayrollStatutoryRuleSet | None:
        qs = PayrollStatutoryRuleSet.objects.filter(
            company=company, is_active=True, effective_from__lte=as_of_date
        ).order_by("-effective_from")
        for r in qs:
            if not r.effective_to or r.effective_to >= as_of_date:
                return r
        return PayrollStatutoryRuleSet.objects.filter(company=company, is_active=True).first()

    @staticmethod
    def compute_monthly_statutory(
        *,
        basic_pay: Decimal,
        gross_pay: Decimal,
        pf_enrolled: bool,
        ssf_enrolled: bool,
        is_married: bool,
        rule_set: PayrollStatutoryRuleSet | None,
    ) -> dict:
        if not rule_set or gross_pay <= 0:
            return {"pf_ssf": Decimal("0.00"), "tds_tax": Decimal("0.00")}

        pf_ssf = Decimal("0.00")
        if ssf_enrolled:
            pf_ssf = (basic_pay * rule_set.employee_ssf_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        elif pf_enrolled:
            pf_ssf = (basic_pay * rule_set.employee_pf_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        annual_taxable = max(Decimal("0.00"), (gross_pay - pf_ssf) * Decimal("12"))
        slabs = (rule_set.tax_slabs_couple if is_married else rule_set.tax_slabs_single) or []
        annual_tax = Decimal("0.00")
        prev_cap = Decimal("0.00")

        for slab in slabs:
            cap = slab.get("upto")
            rate = Decimal(str(slab.get("rate") or "0"))
            if annual_taxable <= prev_cap:
                break
            if cap is None:
                band = annual_taxable - prev_cap
            else:
                cap_dec = Decimal(str(cap))
                band = max(Decimal("0.00"), min(annual_taxable, cap_dec) - prev_cap)
                prev_cap = cap_dec
            annual_tax += band * rate / Decimal("100")

        monthly_tax = (annual_tax / Decimal("12")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        return {"pf_ssf": pf_ssf, "tds_tax": monthly_tax}

