from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import F, Sum
from django.utils import timezone

from apps.accounting.models import Account, AdvanceRecord, CostCenter, Department, EmployeeProfile, PayrollLiability, StaffLoan, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.banking.models import BankAccount
from apps.projects.models import Project
from .formula_engine import SafeSalaryFormulaEngine
from .models import (
    DailyWageEntry,
    EmployeeDetail,
    EmployeeLifecycleChange,
    EmployeeReimbursement,
    EmploymentContract,
    FestivalExpenseRecord,
    FinalSettlement,
    HrConfiguration,
    LeaveBalance,
    LeaveRequest,
    OvertimeRecord,
    PayrollCostAllocation,
    PayrollLine,
    PayrollPaymentBatch,
    PayrollRun,
    PayrollStatutoryRuleSet,
    Payslip,
    PieceRateWorkRecord,
    SalaryComponent,
    SalaryRevision,
    SalaryStructure,
    Timesheet,
)
from .nepal_payroll import NepalPayrollEngine


def _acc(company, role: str | None, code_prefix: str) -> Account | None:
    if role:
        found = Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
        if found:
            return found
    return Account.objects.filter(company=company, code__startswith=code_prefix, is_group=False, is_active=True).first()


def _ensure_hr_account(company, code: str, name: str, account_type: str, control_role: str = "") -> Account:
    existing = Account.objects.filter(company=company, code=code, is_group=False, is_active=True).first()
    if existing:
        return existing
    if control_role:
        by_role = Account.objects.filter(company=company, control_role=control_role, is_group=False, is_active=True).first()
        if by_role:
            return by_role
    parent = Account.objects.filter(company=company, account_type=account_type, is_group=True).first()
    return Account.objects.create(
        company=company,
        code=code,
        name=name,
        account_type=account_type,
        parent=parent,
        control_role=control_role,
        is_group=False,
        is_active=True,
    )


class PayrollProrationAndTaxEngine:
    """Mid-month joining/exit/revision proration + annualized YTD Nepal income tax projection."""

    @staticmethod
    def _prorate_factor(*, emp: EmployeeProfile, detail: EmployeeDetail | None, run: PayrollRun, basis: str) -> tuple[Decimal, Decimal, Decimal]:
        pstart, pend = run.period_start, run.period_end
        cal_days = max(1, (pend - pstart).days + 1)
        divisor = Decimal("30") if basis == SalaryStructure.ProrationMethod.FIXED_30 else Decimal(str(cal_days))
        eff_start = max(pstart, detail.joining_date) if (detail and detail.joining_date) else pstart
        eff_end = min(pend, detail.exit_date) if (detail and detail.exit_date) else pend
        if eff_end < eff_start:
            return Decimal("0.00"), Decimal("0.00"), divisor

        active_days = Decimal(str((eff_end - eff_start).days + 1))
        unpaid_days = (
            LeaveRequest.objects.filter(
                company=run.company, employee=emp, status="APPROVED", is_paid=False,
                start_date__lte=eff_end, end_date__gte=eff_start,
            ).aggregate(s=Sum("days"))["s"]
            or Decimal("0.00")
        )
        payable = max(Decimal("0.00"), active_days - unpaid_days)
        if basis == SalaryStructure.ProrationMethod.FIXED_30 and eff_start == pstart and eff_end == pend and unpaid_days == 0:
            payable = Decimal("30.00")
        ratio = min(Decimal("1.0000"), (payable / divisor).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP))
        return ratio, payable, divisor

    @staticmethod
    def compute_ytd_progressive_tax(
        *,
        company,
        emp: EmployeeProfile,
        pay_date: date,
        current_taxable: Decimal,
        is_married: bool,
        rule_set: PayrollStatutoryRuleSet | None,
    ) -> dict:
        if not rule_set or current_taxable <= 0:
            return {"tds_tax": Decimal("0.00"), "ytd_taxable_income": current_taxable, "ytd_tax_already_paid": Decimal("0.00")}

        fy = company.fiscal_years.filter(start_date__lte=pay_date, end_date__gte=pay_date).first()
        fy_start = fy.start_date if fy else date(pay_date.year, 1, 1)
        prev_agg = PayrollLine.objects.filter(
            payroll_run__company=company,
            employee=emp,
            payroll_run__status__in=[PayrollRun.Status.POSTED, PayrollRun.Status.PAID, PayrollRun.Status.CLOSED],
            payroll_run__pay_date__gte=fy_start,
            payroll_run__pay_date__lt=pay_date,
        ).aggregate(t_inc=Sum("gross_pay"), t_pf=Sum("pf_ssf_deduction"), t_tax=Sum("tds_tax"))

        prev_taxable = (prev_agg["t_inc"] or Decimal("0.00")) - (prev_agg["t_pf"] or Decimal("0.00"))
        prev_paid_tax = prev_agg["t_tax"] or Decimal("0.00")
        prior_runs = PayrollLine.objects.filter(
            payroll_run__company=company,
            employee=emp,
            payroll_run__status__in=[PayrollRun.Status.POSTED, PayrollRun.Status.PAID, PayrollRun.Status.CLOSED],
            payroll_run__pay_date__gte=fy_start,
            payroll_run__pay_date__lt=pay_date,
        ).count()
        remaining_months = max(0, 11 - prior_runs)
        projected_annual = max(
            Decimal("0.00"),
            prev_taxable + current_taxable + (current_taxable * Decimal(str(remaining_months))),
        )

        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 projected_annual <= prev_cap:
                break
            if cap is None:
                band = projected_annual - prev_cap
            else:
                cap_dec = Decimal(str(cap))
                band = max(Decimal("0.00"), min(projected_annual, cap_dec) - prev_cap)
                prev_cap = cap_dec
            annual_tax += band * rate / Decimal("100")

        rem_periods = Decimal(str(remaining_months + 1))
        monthly_tds = max(
            Decimal("0.00"),
            ((annual_tax - prev_paid_tax) / rem_periods).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP),
        )
        return {
            "tds_tax": monthly_tds,
            "ytd_taxable_income": (prev_taxable + current_taxable).quantize(Decimal("0.01")),
            "ytd_tax_already_paid": prev_paid_tax.quantize(Decimal("0.01")),
        }

    @staticmethod
    @transaction.atomic
    def calculate_enterprise_payroll_run(
        *,
        run: PayrollRun,
        user,
        use_ytd_tax: bool = True,
        proration_basis_override: str | None = None,
    ) -> PayrollRun:
        run = PayrollRun.objects.select_for_update().get(id=run.id)
        if run.status in (PayrollRun.Status.POSTED, PayrollRun.Status.PAID, PayrollRun.Status.CLOSED):
            raise ValidationError("Cannot recalculate an already POSTED/PAID/CLOSED payroll run.")

        if not run.statutory_rule_set:
            run.statutory_rule_set = NepalPayrollEngine.get_active_ruleset(run.company, run.pay_date)

        run.lines.all().delete()
        warnings: list[dict] = []
        emp_qs = EmployeeProfile.objects.filter(company=run.company, is_active=True).select_related("project", "department")
        if run.project_id:
            emp_qs = emp_qs.filter(project_id=run.project_id)

        tot_gross = Decimal("0.00")
        tot_ded = Decimal("0.00")
        tot_net = Decimal("0.00")
        tot_er = Decimal("0.00")
        cfg = HrConfiguration.objects.filter(company=run.company).first()
        custom_components = list(SalaryComponent.objects.filter(company=run.company, is_active=True, calc_method=SalaryComponent.CalcMethod.FORMULA))

        for emp in emp_qs:
            detail = getattr(emp, "hr_detail", None)
            if detail and detail.status not in (EmployeeDetail.Status.ACTIVE, EmployeeDetail.Status.ON_LEAVE):
                continue

            sal = SalaryStructure.objects.filter(company=run.company, employee=emp, is_current=True).first()
            basis = proration_basis_override or (sal.proration_method if sal else (cfg.default_proration_method if cfg else "CALENDAR_DAYS"))
            ratio, payable_days, divisor_days = PayrollProrationAndTaxEngine._prorate_factor(emp=emp, detail=detail, run=run, basis=basis)

            # Check approved mid-month salary revisions -> split prorated basic across effective_from
            revs = list(
                SalaryRevision.objects.filter(
                    company=run.company, employee=emp, status="APPROVED",
                    effective_from__gt=run.period_start, effective_from__lte=run.period_end,
                ).order_by("effective_from")
            )
            full_basic = sal.basic_salary if sal else emp.basic_salary
            full_allow = ((sal.dearness_allowance + sal.site_allowance + sal.conveyance_allowance + sal.house_rent_allowance) if sal else Decimal("0.00"))

            if revs and ratio > 0:
                total_cal = max(1, (run.period_end - run.period_start).days + 1)
                split_rev = revs[-1]
                pre_days = Decimal(str((split_rev.effective_from - run.period_start).days))
                post_days = Decimal(str(total_cal - int(pre_days)))
                basic = (
                    (split_rev.previous_basic * pre_days / Decimal(str(total_cal)))
                    + (split_rev.new_basic * post_days / Decimal(str(total_cal)))
                ).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            else:
                basic = (full_basic * ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

            allow = (full_allow * ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

            # Evaluate custom formula components safely
            formula_bonus = Decimal("0.00")
            for comp in custom_components:
                if comp.component_type == SalaryComponent.ComponentType.EARNING and comp.formula_expression:
                    val = SafeSalaryFormulaEngine.evaluate(
                        comp.formula_expression,
                        {"BASIC": basic, "GROSS": basic + allow, "WORKED_DAYS": payable_days, "SCHEDULED_DAYS": divisor_days},
                    )
                    formula_bonus += val

            # Approved OT (strictly ignore unapproved)
            ot_hrs = Decimal("0.00")
            ot_pay = (
                OvertimeRecord.objects.filter(
                    company=run.company, employee=emp, status="HR_APPROVED",
                    ot_date__gte=run.period_start, ot_date__lte=run.period_end,
                ).aggregate(s=Sum("calculated_amount"))["s"]
                or Decimal("0.00")
            )
            if OvertimeRecord.objects.filter(company=run.company, employee=emp, status="PENDING", ot_date__gte=run.period_start, ot_date__lte=run.period_end).exists():
                warnings.append({"employee_code": emp.employee_code, "message": "Unapproved overtime excluded from payroll run."})

            # Timesheets, Daily Wages & Piece Rate
            ts_cost = (
                Timesheet.objects.filter(
                    company=run.company, employee=emp, status=Timesheet.Status.APPROVED,
                    period_start__gte=run.period_start, period_end__lte=run.period_end,
                ).aggregate(s=Sum("total_labor_cost"))["s"]
                or Decimal("0.00")
            )
            dw_pay = (
                DailyWageEntry.objects.filter(
                    company=run.company, employee=emp, status="APPROVED",
                    work_date__gte=run.period_start, work_date__lte=run.period_end,
                ).aggregate(s=Sum("net_payable"))["s"]
                or Decimal("0.00")
            )
            pr_pay = (
                PieceRateWorkRecord.objects.filter(
                    company=run.company, employee=emp, status="APPROVED", quality_approved=True,
                    work_date__gte=run.period_start, work_date__lte=run.period_end,
                ).aggregate(s=Sum("total_amount"))["s"]
                or Decimal("0.00")
            )

            if detail and detail.employment_type in (
                EmployeeDetail.EmploymentType.DAILY_WAGE,
                EmployeeDetail.EmploymentType.SKILLED_LABOR,
                EmployeeDetail.EmploymentType.UNSKILLED_LABOR,
            ):
                basic = Decimal("0.00")
                allow = Decimal("0.00")
                ot_pay = (ot_pay + ts_cost + dw_pay + pr_pay).quantize(Decimal("0.01"))
            else:
                ot_pay = (ot_pay + formula_bonus).quantize(Decimal("0.01"))

            fest_amt = (
                FestivalExpenseRecord.objects.filter(company=run.company, employee=emp, status="APPROVED").aggregate(s=Sum("entitled_amount"))["s"]
                or Decimal("0.00")
            )
            reimb_amt = (
                EmployeeReimbursement.objects.filter(
                    company=run.company, employee=emp, status="APPROVED",
                    claim_date__gte=run.period_start, claim_date__lte=run.period_end,
                ).aggregate(s=Sum("approved_amount"))["s"]
                or Decimal("0.00")
            )

            remuneration_gross = (basic + allow + ot_pay + fest_amt).quantize(Decimal("0.01"))
            if remuneration_gross <= 0 and reimb_amt <= 0:
                continue

            if detail and not detail.bank_account_no and detail.payment_method == "BANK_TRANSFER":
                warnings.append({"employee_code": emp.employee_code, "message": "Missing employee bank account for Bank Transfer."})

            rs = run.statutory_rule_set
            emp_ssf_pf = Decimal("0.00")
            er_ssf = Decimal("0.00")
            er_pf = Decimal("0.00")
            gratuity = Decimal("0.00")
            if rs and basic > 0:
                if detail and detail.ssf_enrolled:
                    emp_ssf_pf = (basic * rs.employee_ssf_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                    er_ssf = (basic * rs.employer_ssf_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                elif detail and detail.pf_enrolled:
                    emp_ssf_pf = (basic * rs.employee_pf_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                    er_pf = (basic * rs.employer_pf_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
                if not (detail and detail.ssf_enrolled) and rs.gratuity_pct > 0:
                    gratuity = (basic * rs.gratuity_pct / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

            taxable_period = max(Decimal("0.00"), remuneration_gross - emp_ssf_pf)
            if use_ytd_tax:
                tax_info = PayrollProrationAndTaxEngine.compute_ytd_progressive_tax(
                    company=run.company, emp=emp, pay_date=run.pay_date,
                    current_taxable=taxable_period, is_married=bool(detail and detail.is_married_tax), rule_set=rs,
                )
            else:
                st = NepalPayrollEngine.compute_monthly_statutory(
                    basic_pay=basic, gross_pay=remuneration_gross,
                    pf_enrolled=bool(detail and detail.pf_enrolled),
                    ssf_enrolled=bool(detail and detail.ssf_enrolled),
                    is_married=bool(detail and detail.is_married_tax), rule_set=rs,
                )
                tax_info = {"tds_tax": st["tds_tax"], "ytd_taxable_income": taxable_period, "ytd_tax_already_paid": Decimal("0.00")}

            tds = tax_info["tds_tax"]

            adv_rec = (
                AdvanceRecord.objects.select_for_update()
                .filter(
                    company=run.company, employee=emp,
                    advance_type=AdvanceRecord.AdvanceType.EMPLOYEE_ADVANCE,
                    status__in=[AdvanceRecord.Status.OPEN, AdvanceRecord.Status.PARTIALLY_ADJUSTED],
                )
                .first()
            )
            loan = (
                StaffLoan.objects.select_for_update()
                .filter(company=run.company, employee=emp, status=StaffLoan.Status.ACTIVE)
                .first()
            )

            rem_cash = max(Decimal("0.00"), remuneration_gross + reimb_amt - emp_ssf_pf - tds)
            adv_ded = Decimal("0.00")
            if adv_rec and rem_cash > 0:
                adv_ded = min(adv_rec.remaining_amount, rem_cash)
                rem_cash -= adv_ded
            loan_ded = Decimal("0.00")
            if loan and rem_cash > 0:
                loan_ded = min(loan.monthly_installment, loan.remaining_principal, rem_cash)
                rem_cash -= loan_ded

            net = max(Decimal("0.00"), (remuneration_gross + reimb_amt - emp_ssf_pf - tds - adv_ded - loan_ded)).quantize(Decimal("0.01"))
            ded = (emp_ssf_pf + tds + adv_ded + loan_ded).quantize(Decimal("0.01"))
            er_cost = (remuneration_gross + reimb_amt + er_ssf + er_pf + gratuity).quantize(Decimal("0.01"))

            tot_gross += (remuneration_gross + reimb_amt)
            tot_ded += ded
            tot_net += net
            tot_er += (er_ssf + er_pf + gratuity)

            PayrollLine.objects.create(
                payroll_run=run,
                employee=emp,
                project=emp.project or run.project,
                proration_basis=basis,
                payable_days=payable_days,
                total_period_days=divisor_days,
                basic_pay=basic,
                allowances=allow,
                overtime_pay=ot_pay,
                bonus_festival=fest_amt,
                reimbursements=reimb_amt,
                gross_pay=(remuneration_gross + reimb_amt),
                pf_ssf_deduction=emp_ssf_pf,
                tds_tax=tds,
                advance_recovery=adv_ded,
                loan_deduction=loan_ded,
                net_pay=net,
                employer_ssf=er_ssf,
                employer_pf=er_pf,
                gratuity_accrual=gratuity,
                employer_total_cost=er_cost,
                ytd_taxable_income=tax_info["ytd_taxable_income"],
                ytd_tax_already_paid=tax_info["ytd_tax_already_paid"],
                line_breakdown_json={
                    "proration_ratio": str(ratio),
                    "payable_days": str(payable_days),
                    "divisor_days": str(divisor_days),
                    "revisions_applied": len(revs),
                    "formula_bonus": str(formula_bonus),
                    "daily_wage_added": str(dw_pay),
                    "piece_rate_added": str(pr_pay),
                },
                advance_record=adv_rec if adv_ded > 0 else None,
                staff_loan=loan if loan_ded > 0 else None,
            )

        run.total_gross = tot_gross
        run.total_deductions = tot_ded
        run.total_net_pay = tot_net
        run.employer_contribution_total = tot_er
        run.validation_warnings_json = warnings
        run.calculation_version += 1
        run.attendance_frozen_at = run.attendance_frozen_at or timezone.now()
        run.status = PayrollRun.Status.CALCULATED
        run.version += 1
        run.save()
        return run


class PayrollAccountingAndPaymentEngine:
    """Posts separate Employer Contributions, Non-Duplicating Project WIP Allocations & Confirmed Salary Payments."""

    @staticmethod
    @transaction.atomic
    def post_enterprise_payroll(*, run: PayrollRun, user) -> PayrollRun:
        run = PayrollRun.objects.select_for_update().get(id=run.id)
        if run.status == PayrollRun.Status.POSTED:
            return run
        if run.status != PayrollRun.Status.APPROVED:
            raise ValidationError("Payroll run must be APPROVED before posting to GL.")

        exp_acc = _acc(run.company, Account.ControlRole.DIRECT_EXPENSES, "5020")
        wage_acc = _acc(run.company, Account.ControlRole.WAGES_PAYABLE, "2035")
        pf_acc = _acc(run.company, Account.ControlRole.PF_SSF_PAYABLE, "2045")
        tds_acc = _acc(run.company, Account.ControlRole.TDS_PAYABLE, "2120")
        adv_acc = _acc(run.company, Account.ControlRole.EMPLOYEE_ADVANCE, "1170")
        loan_acc = _acc(run.company, Account.ControlRole.STAFF_LOAN_RECEIVABLE, "1175")
        if not exp_acc or not wage_acc:
            raise ValidationError("Salary Expense (5020) and Wages Payable (2035) accounts are required.")

        er_exp_acc = _ensure_hr_account(run.company, "5025", "Employer SSF/PF & Gratuity Expense", Account.AccountType.EXPENSE)
        grat_pay_acc = _ensure_hr_account(run.company, "2048", "Employee Gratuity Payable", Account.AccountType.LIABILITY)

        gl_lines = []
        tot_emp_er_pf_ssf = Decimal("0.00")
        tot_gratuity = Decimal("0.00")
        tot_tds = Decimal("0.00")

        for pl in run.lines.select_related("employee__party", "project", "advance_record", "staff_loan"):
            emp = pl.employee
            gl_lines.append({
                "account": exp_acc, "debit": pl.gross_pay, "credit": Decimal("0.00"),
                "project": pl.project or run.project, "employee_ref": emp.employee_code,
                "description": f"Payroll Salary & Wage: {emp.full_name} ({run.period_label})",
            })
            er_stat = (pl.employer_ssf + pl.employer_pf).quantize(Decimal("0.01"))
            er_all = (er_stat + pl.gratuity_accrual).quantize(Decimal("0.01"))
            if er_all > 0:
                gl_lines.append({
                    "account": er_exp_acc, "debit": er_all, "credit": Decimal("0.00"),
                    "project": pl.project or run.project, "employee_ref": emp.employee_code,
                    "description": f"Employer Contribution & Gratuity: {emp.full_name}",
                })
            if pl.net_pay > 0:
                gl_lines.append({
                    "account": wage_acc, "party": emp.party, "debit": Decimal("0.00"), "credit": pl.net_pay,
                    "project": pl.project or run.project, "employee_ref": emp.employee_code,
                    "description": f"Net Salary Payable: {emp.full_name}",
                })
            if pl.advance_recovery > 0 and adv_acc and pl.advance_record:
                gl_lines.append({
                    "account": adv_acc, "party": emp.party, "advance_record": pl.advance_record,
                    "debit": Decimal("0.00"), "credit": pl.advance_recovery,
                    "project": pl.project or run.project, "description": f"Advance Recovery: {emp.full_name}",
                })
            if pl.loan_deduction > 0 and loan_acc and pl.staff_loan:
                gl_lines.append({
                    "account": loan_acc, "party": emp.party, "staff_loan": pl.staff_loan,
                    "debit": Decimal("0.00"), "credit": pl.loan_deduction,
                    "project": pl.project or run.project, "description": f"Staff Loan Deduction: {emp.full_name}",
                })
            tot_emp_er_pf_ssf += (pl.pf_ssf_deduction + er_stat)
            tot_gratuity += pl.gratuity_accrual
            tot_tds += pl.tds_tax

        if tot_emp_er_pf_ssf > 0:
            if not pf_acc:
                raise ValidationError("PF / SSF Payable account (control_role=PF_SSF_PAYABLE) is required.")
            gl_lines.append({"account": pf_acc, "debit": Decimal("0.00"), "credit": tot_emp_er_pf_ssf, "description": f"Employee + Employer SSF/PF Payable ({run.run_no})"})
        if tot_gratuity > 0:
            gl_lines.append({"account": grat_pay_acc, "debit": Decimal("0.00"), "credit": tot_gratuity, "description": f"Gratuity Provision Payable ({run.run_no})"})
        if tot_tds > 0:
            if not tds_acc:
                raise ValidationError("TDS Payable account (control_role=TDS_PAYABLE) is required.")
            gl_lines.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tot_tds, "description": f"Salary TDS Payable ({run.run_no})"})

        v = VoucherService.create_draft(
            company=run.company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.PAYROLL,
                "voucher_date": run.pay_date,
                "project": run.project,
                "reference_no": run.run_no,
                "narration": f"Enterprise Payroll Accrual {run.run_no} — {run.period_label}",
                "gross_amount": run.total_gross + run.employer_contribution_total,
                "tds_amount": tot_tds,
                "net_amount": run.total_net_pay,
                "is_control_override": True,
                "override_reason": "Enterprise Multi-Employee Payroll Journal",
            },
            lines_data=gl_lines,
        )
        v.status = Voucher.Status.APPROVED
        v.approved_by = user
        v.save(update_fields=["status", "approved_by"])
        v = PostingService.post_voucher(voucher=v, user=user)

        for idx, pl in enumerate(run.lines.select_related("employee"), start=1):
            PayrollLiability.objects.get_or_create(
                company=run.company,
                payroll_ref=f"{run.run_no}-{pl.employee.employee_code}",
                employee=pl.employee,
                defaults={
                    "project": pl.project or run.project,
                    "period_label": run.period_label,
                    "control_account": wage_acc,
                    "source_voucher": v,
                    "gross_wages": pl.net_pay,
                },
            )
            Payslip.objects.get_or_create(
                company=run.company, payroll_line=pl, defaults={"payslip_no": f"PSL-{run.run_no}-{idx:03d}"}
            )

        run.accrual_voucher = v
        run.status = PayrollRun.Status.POSTED
        run.version += 1
        run.save(update_fields=["accrual_voucher", "status", "version"])
        return run

    @staticmethod
    @transaction.atomic
    def allocate_project_labour_cost(*, run: PayrollRun, user, allocations: list[dict] | None = None) -> Voucher:
        """Transfers project-attributable labour cost to Project WIP without duplicating payroll expense."""
        run = PayrollRun.objects.select_for_update().get(id=run.id)
        if run.project_wip_voucher_id:
            return run.project_wip_voucher
        wip_acc = _ensure_hr_account(run.company, "1360", "Project Direct Labour WIP", Account.AccountType.ASSET)
        clearing_acc = _ensure_hr_account(run.company, "5029", "Salary Allocation Clearing", Account.AccountType.EXPENSE)

        rows = []
        if allocations:
            for a in allocations:
                emp = EmployeeProfile.objects.get(company=run.company, id=a["employee_id"])
                proj = Project.objects.get(company=run.company, id=a["project_id"])
                amt = Decimal(str(a["allocated_amount"])).quantize(Decimal("0.01"))
                rows.append((emp, proj, amt, Decimal(str(a.get("allocation_pct") or "100.00"))))
        else:
            for pl in run.lines.select_related("employee", "project"):
                if pl.project_id:
                    rows.append((pl.employee, pl.project, pl.employer_total_cost, Decimal("100.00")))

        if not rows:
            raise ValidationError("No project-assigned payroll lines found for WIP allocation.")

        gl_lines = []
        tot_amt = Decimal("0.00")
        for emp, proj, amt, pct in rows:
            if amt <= 0:
                continue
            PayrollCostAllocation.objects.create(
                company=run.company, payroll_run=run, employee=emp, project=proj,
                allocation_pct=pct, allocated_amount=amt, is_wip=True,
            )
            gl_lines.append({"account": wip_acc, "debit": amt, "credit": Decimal("0.00"), "project": proj, "description": f"Project Labour WIP: {emp.full_name}"})
            tot_amt += amt

        gl_lines.append({"account": clearing_acc, "debit": Decimal("0.00"), "credit": tot_amt, "description": f"Payroll Allocation Clearing ({run.run_no})"})
        v = VoucherService.create_draft(
            company=run.company, user=user,
            data={"voucher_type": Voucher.VoucherType.PROJECT_COST_TRANSFER, "voucher_date": run.pay_date, "narration": f"Project Labour WIP Allocation ({run.run_no})", "gross_amount": tot_amt, "net_amount": tot_amt},
            lines_data=gl_lines,
        )
        v.status = Voucher.Status.APPROVED
        v.approved_by = user
        v.save(update_fields=["status", "approved_by"])
        v = PostingService.post_voucher(voucher=v, user=user)
        run.project_wip_voucher = v
        run.save(update_fields=["project_wip_voucher"])
        return v

    @staticmethod
    @transaction.atomic
    def create_or_confirm_payment_batch(*, company, run: PayrollRun, bank_account_id: str | None, payment_method: str, confirm_now: bool, user) -> PayrollPaymentBatch:
        run = PayrollRun.objects.select_for_update().get(id=run.id, company=company)
        if run.status not in (PayrollRun.Status.POSTED, PayrollRun.Status.PARTIALLY_PAID):
            raise ValidationError("Payroll run must be POSTED before salary payment disbursement.")
        if run.total_net_pay <= 0:
            raise ValidationError("No net payable salary remaining for payment.")

        bank = BankAccount.objects.filter(company=company, id=bank_account_id).first() if bank_account_id else None
        batch_no = f"PAYB-{run.run_no}-{PayrollPaymentBatch.objects.filter(company=company).count() + 1:03d}"
        batch = PayrollPaymentBatch.objects.create(
            company=company,
            payroll_run=run,
            batch_no=batch_no,
            payment_method=payment_method or "BANK_TRANSFER",
            bank_account=bank,
            total_amount=run.total_net_pay,
            status="EXPORTED",
        )
        if not confirm_now:
            return batch

        wage_acc = _acc(company, Account.ControlRole.WAGES_PAYABLE, "2035")
        pay_gl = bank.gl_account if bank else _acc(company, Account.ControlRole.CASH, "1010")
        if not wage_acc or not pay_gl:
            raise ValidationError("Wages Payable and Bank/Cash GL account are required to confirm payment.")

        gl_lines = []
        for pl in run.lines.select_related("employee__party"):
            if pl.net_pay > 0:
                gl_lines.append({
                    "account": wage_acc, "party": pl.employee.party, "debit": pl.net_pay, "credit": Decimal("0.00"),
                    "description": f"Salary Payment: {pl.employee.full_name} ({run.run_no})",
                })
        gl_lines.append({
            "account": pay_gl, "debit": Decimal("0.00"), "credit": run.total_net_pay,
            "description": f"Salary Bank Disbursement Batch {batch_no}",
        })
        v = VoucherService.create_draft(
            company=company, user=user,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": date.today(), "narration": f"Salary Payment Batch {batch_no}", "gross_amount": run.total_net_pay, "net_amount": run.total_net_pay, "is_control_override": True, "override_reason": "Multi-Employee Salary Batch"},
            lines_data=gl_lines,
        )
        v.status = Voucher.Status.APPROVED
        v.approved_by = user
        v.save(update_fields=["status", "approved_by"])
        v = PostingService.post_voucher(voucher=v, user=user)

        PayrollLiability.objects.filter(company=company, payroll_ref__startswith=f"{run.run_no}-").update(settled_amount=F("gross_wages"), status=PayrollLiability.Status.SETTLED)
        batch.status = "CONFIRMED"
        batch.confirmed_at = timezone.now()
        batch.confirmed_by = user
        batch.voucher = v
        batch.save()
        run.payment_voucher = v
        run.status = PayrollRun.Status.PAID
        run.save(update_fields=["payment_voucher", "status"])
        return batch


class EmployeeLifecycleAndSettlementEngine:
    """Handles contracts, transfers, salary revisions, reimbursements, festival pay & final exit settlements."""

    @staticmethod
    @transaction.atomic
    def apply_lifecycle_change(*, company, employee: EmployeeProfile, actor, data: dict) -> EmployeeLifecycleChange:
        eff_date = data.get("effective_date") or date.today()
        if isinstance(eff_date, str):
            eff_date = date.fromisoformat(eff_date)
        ctype = (data.get("change_type") or "INCREMENT").upper()
        detail = getattr(employee, "hr_detail", None)
        prev = {
            "basic_salary": str(employee.basic_salary),
            "designation": employee.designation,
            "project_id": str(employee.project_id) if employee.project_id else None,
            "department_id": str(employee.department_id) if employee.department_id else None,
        }
        new_vals = {}
        if data.get("new_designation"):
            employee.designation = data["new_designation"]
            new_vals["designation"] = data["new_designation"]
        if data.get("new_project_id"):
            employee.project = Project.objects.get(company=company, id=data["new_project_id"])
            new_vals["project_id"] = str(employee.project_id)
        if data.get("new_department_id"):
            employee.department = Department.objects.get(company=company, id=data["new_department_id"])
            new_vals["department_id"] = str(employee.department_id)

        if data.get("new_basic") is not None:
            nb = Decimal(str(data["new_basic"])).quantize(Decimal("0.01"))
            old_b = employee.basic_salary
            SalaryStructure.objects.filter(company=company, employee=employee, is_current=True).update(
                is_current=False, effective_to=eff_date - timedelta(days=1)
            )
            cur = SalaryStructure.objects.filter(company=company, employee=employee).order_by("-effective_from").first()
            new_sal = SalaryStructure.objects.create(
                company=company,
                employee=employee,
                effective_from=eff_date,
                basic_salary=nb,
                dearness_allowance=cur.dearness_allowance if cur else Decimal("0.00"),
                site_allowance=cur.site_allowance if cur else Decimal("0.00"),
                conveyance_allowance=cur.conveyance_allowance if cur else Decimal("0.00"),
                house_rent_allowance=cur.house_rent_allowance if cur else Decimal("0.00"),
                approved_by=actor,
                is_current=True,
                version=(cur.version + 1) if cur else 1,
            )
            SalaryRevision.objects.create(
                company=company, employee=employee, effective_from=eff_date,
                previous_basic=old_b, new_basic=nb, revision_type=ctype,
                new_structure=new_sal, status="APPROVED", reason=data.get("reason", ""), approved_by=actor,
            )
            employee.basic_salary = nb
            new_vals["basic_salary"] = str(nb)

        employee.save()
        if detail and data.get("new_project_id"):
            detail.assigned_project = employee.project
            detail.save(update_fields=["assigned_project"])

        return EmployeeLifecycleChange.objects.create(
            company=company, employee=employee, change_type=ctype, effective_date=eff_date,
            previous_value=prev, new_value=new_vals, reason=data.get("reason", ""),
            status="APPROVED", prepared_by=actor, approved_by=actor,
        )

    @staticmethod
    @transaction.atomic
    def calculate_and_post_final_settlement(*, company, employee: EmployeeProfile, actor, data: dict) -> FinalSettlement:
        detail = getattr(employee, "hr_detail", None)
        last_dt = data.get("last_working_date") or date.today()
        if isinstance(last_dt, str):
            last_dt = date.fromisoformat(last_dt)

        unpaid_sal = Decimal(str(data.get("unpaid_salary") or "0.00"))
        pend_ot = Decimal(str(
            data.get("pending_overtime")
            or OvertimeRecord.objects.filter(company=company, employee=employee, status="HR_APPROVED").aggregate(s=Sum("calculated_amount"))["s"]
            or "0.00"
        ))
        sal = SalaryStructure.objects.filter(company=company, employee=employee, is_current=True).first()
        basic = sal.basic_salary if sal else employee.basic_salary
        daily_basic = (basic / Decimal("30")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        leave_enc = Decimal("0.00")
        for lb in LeaveBalance.objects.filter(company=company, employee=employee):
            avail = max(Decimal("0.00"), lb.opening_balance + lb.accrued_days + lb.adjusted_days - lb.taken_days - lb.encashed_days)
            leave_enc += (avail * daily_basic).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        if data.get("leave_encashment") is not None:
            leave_enc = Decimal(str(data["leave_encashment"]))

        grat = Decimal(str(data.get("gratuity_settlement") or "0.00"))
        fest = Decimal(str(data.get("festival_prorata") or "0.00"))

        adv_bal = sum(
            (a.remaining_amount for a in AdvanceRecord.objects.select_for_update().filter(
                company=company, employee=employee, status__in=[AdvanceRecord.Status.OPEN, AdvanceRecord.Status.PARTIALLY_ADJUSTED]
            )),
            Decimal("0.00"),
        )
        loan_bal = sum(
            (l.remaining_principal for l in StaffLoan.objects.select_for_update().filter(company=company, employee=employee, status=StaffLoan.Status.ACTIVE)),
            Decimal("0.00"),
        )
        tax_adj = Decimal(str(data.get("tax_adjustment") or "0.00"))

        earnings = (unpaid_sal + pend_ot + leave_enc + grat + fest).quantize(Decimal("0.01"))
        net = max(Decimal("0.00"), earnings - adv_bal - loan_bal - tax_adj).quantize(Decimal("0.01"))

        settlement, _ = FinalSettlement.objects.update_or_create(
            company=company,
            employee=employee,
            defaults={
                "exit_type": data.get("exit_type") or "RESIGNATION",
                "last_working_date": last_dt,
                "unpaid_salary": unpaid_sal,
                "pending_overtime": pend_ot,
                "leave_encashment": leave_enc,
                "gratuity_settlement": grat,
                "festival_prorata": fest,
                "advance_recovery": adv_bal,
                "loan_recovery": loan_bal,
                "tax_adjustment": tax_adj,
                "net_payable": net,
                "clearance_json": data.get("clearance") or {"asset": True, "department": True, "finance": True, "hr": True},
                "status": "APPROVED" if data.get("post_voucher") else "CALCULATED",
                "approved_by": actor if data.get("post_voucher") else None,
            },
        )

        if data.get("post_voucher") and earnings > 0:
            exp_acc = _acc(company, Account.ControlRole.DIRECT_EXPENSES, "5020")
            wage_acc = _acc(company, Account.ControlRole.WAGES_PAYABLE, "2035")
            adv_acc = _acc(company, Account.ControlRole.EMPLOYEE_ADVANCE, "1170")
            loan_acc = _acc(company, Account.ControlRole.STAFF_LOAN_RECEIVABLE, "1175")
            tds_acc = _acc(company, Account.ControlRole.TDS_PAYABLE, "2120")
            lines = [{"account": exp_acc, "debit": earnings, "credit": Decimal("0.00"), "description": f"Final Exit Settlement: {employee.full_name}"}]
            if net > 0:
                lines.append({"account": wage_acc, "party": employee.party, "debit": Decimal("0.00"), "credit": net, "description": f"Final Settlement Payable: {employee.full_name}"})
            if adv_bal > 0 and adv_acc:
                lines.append({"account": adv_acc, "party": employee.party, "debit": Decimal("0.00"), "credit": adv_bal, "description": f"Exit Advance Recovery: {employee.full_name}"})
            if loan_bal > 0 and loan_acc:
                lines.append({"account": loan_acc, "party": employee.party, "debit": Decimal("0.00"), "credit": loan_bal, "description": f"Exit Loan Recovery: {employee.full_name}"})
            if tax_adj > 0 and tds_acc:
                lines.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tax_adj, "description": f"Exit TDS Tax Adjustment: {employee.full_name}"})

            v = VoucherService.create_draft(
                company=company, user=actor,
                data={"voucher_type": Voucher.VoucherType.PAYROLL, "voucher_date": last_dt, "narration": f"Final Settlement — {employee.full_name}", "gross_amount": earnings, "net_amount": net, "is_control_override": True, "override_reason": "Final Exit Settlement"},
                lines_data=lines,
            )
            v.status = Voucher.Status.APPROVED
            v.approved_by = actor
            v.save(update_fields=["status", "approved_by"])
            v = PostingService.post_voucher(voucher=v, user=actor)
            settlement.voucher = v
            settlement.status = "POSTED"
            settlement.save(update_fields=["voucher", "status"])

        if data.get("deactivate_employee"):
            employee.is_active = False
            employee.save(update_fields=["is_active"])
            if detail:
                detail.exit_date = last_dt
                detail.status = EmployeeDetail.Status.TERMINATED if settlement.exit_type == "TERMINATION" else EmployeeDetail.Status.RESIGNED
                detail.save(update_fields=["exit_date", "status"])
                if detail.user_id:
                    detail.user.is_active = False
                    detail.user.save(update_fields=["is_active"])

        return settlement

