from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction

from apps.accounting.models import Account, AdvanceRecord, EmployeeProfile, PayrollLiability, StaffLoan, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from .models import (
    AttendanceRecord,
    EmployeeDetail,
    PayrollLine,
    PayrollRun,
    Payslip,
    SalaryStructure,
    Timesheet,
    TimesheetLine,
)
from .nepal_payroll import NepalPayrollEngine


def _find_acc(company, role: str, fallback: str) -> Account | None:
    return (
        Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
        or Account.objects.filter(company=company, code__startswith=fallback, is_group=False, is_active=True).first()
    )


class HrService:
    @staticmethod
    @transaction.atomic
    def upsert_attendance(*, company, user, data: dict) -> AttendanceRecord:
        existing = AttendanceRecord.objects.filter(
            company=company, employee=data["employee"], attendance_date=data["attendance_date"]
        ).first()
        if existing:
            snap = existing.original_snapshot or {
                "status": existing.status,
                "overtime_hours": str(existing.overtime_hours),
            }
            existing.status = data.get("status", existing.status)
            existing.overtime_hours = Decimal(str(data.get("overtime_hours") or existing.overtime_hours))
            existing.check_in = data.get("check_in", existing.check_in)
            existing.check_out = data.get("check_out", existing.check_out)
            existing.original_snapshot = snap
            existing.approved_by = user
            existing.save()
            return existing
        return AttendanceRecord.objects.create(
            company=company,
            employee=data["employee"],
            project=data.get("project"),
            site=data.get("site"),
            shift=data.get("shift"),
            attendance_date=data["attendance_date"],
            check_in=data.get("check_in"),
            check_out=data.get("check_out"),
            overtime_hours=Decimal(str(data.get("overtime_hours") or "0.00")),
            status=data.get("status", AttendanceRecord.Status.PRESENT),
            source=data.get("source", "MANUAL"),
        )

    @staticmethod
    @transaction.atomic
    def create_timesheet(*, company, user, data: dict, lines_data: list[dict]) -> Timesheet:
        emp: EmployeeProfile = data["employee"]
        detail = getattr(emp, "hr_detail", None)
        default_rate = detail.hourly_rate if detail else Decimal("250.00")
        ot_mult = detail.shift.overtime_multiplier if (detail and detail.shift) else Decimal("1.50")

        ts = Timesheet.objects.create(
            company=company,
            timesheet_no=data["timesheet_no"],
            employee=emp,
            project=data["project"],
            site=data.get("site"),
            period_start=data["period_start"],
            period_end=data["period_end"],
            submitted_by=user,
            status=Timesheet.Status.DRAFT,
        )
        reg_sum = Decimal("0.00")
        ot_sum = Decimal("0.00")
        cost_sum = Decimal("0.00")
        for row in lines_data:
            rh = Decimal(str(row.get("regular_hours") or "0.00"))
            oh = Decimal(str(row.get("overtime_hours") or "0.00"))
            hrate = Decimal(str(row.get("hourly_rate") or default_rate))
            orate = Decimal(str(row.get("overtime_rate") or (hrate * ot_mult))).quantize(Decimal("0.01"))
            lcost = ((rh * hrate) + (oh * orate)).quantize(Decimal("0.01"))
            reg_sum += rh
            ot_sum += oh
            cost_sum += lcost
            TimesheetLine.objects.create(
                timesheet=ts,
                work_date=row["work_date"],
                work_activity=row["work_activity"],
                cost_code=row.get("cost_code"),
                boq_item=row.get("boq_item"),
                regular_hours=rh,
                overtime_hours=oh,
                hourly_rate=hrate,
                overtime_rate=orate,
                labor_cost=lcost,
            )
        ts.total_regular_hours = reg_sum
        ts.total_overtime_hours = ot_sum
        ts.total_labor_cost = cost_sum
        ts.save(update_fields=["total_regular_hours", "total_overtime_hours", "total_labor_cost"])
        return ts

    @staticmethod
    @transaction.atomic
    def approve_timesheet(*, ts: Timesheet, user) -> Timesheet:
        ts = Timesheet.objects.select_for_update().get(pk=ts.pk)
        ts.status = Timesheet.Status.APPROVED
        ts.approved_by = user
        ts.save(update_fields=["status", "approved_by"])
        return ts

    @staticmethod
    @transaction.atomic
    def create_and_calculate_payroll(*, company, user, data: dict) -> PayrollRun:
        rule_set = NepalPayrollEngine.get_active_ruleset(company, data["pay_date"])
        run = PayrollRun.objects.create(
            company=company,
            run_no=data["run_no"],
            period_label=data["period_label"],
            period_start=data["period_start"],
            period_end=data["period_end"],
            pay_date=data["pay_date"],
            project=data.get("project"),
            statutory_rule_set=rule_set,
            created_by=user,
            status=PayrollRun.Status.DRAFT,
        )
        return HrService.calculate_payroll(run=run)

    @staticmethod
    @transaction.atomic
    def calculate_payroll(*, run: PayrollRun) -> PayrollRun:
        run.lines.all().delete()
        emp_qs = EmployeeProfile.objects.select_related("project", "hr_detail").filter(company=run.company, is_active=True)
        if run.project_id:
            emp_qs = emp_qs.filter(project=run.project)

        tot_gross = Decimal("0.00")
        tot_ded = Decimal("0.00")
        tot_net = Decimal("0.00")

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

            sal = SalaryStructure.objects.filter(company=run.company, employee=emp, is_current=True).first()
            ts_list = list(
                Timesheet.objects.filter(
                    company=run.company, employee=emp, status=Timesheet.Status.APPROVED,
                    period_start__gte=run.period_start, period_end__lte=run.period_end,
                )
            )
            ts_cost = sum((t.total_labor_cost for t in ts_list), Decimal("0.00"))
            basic = sal.basic_salary if sal else emp.basic_salary
            allow = (sal.dearness_allowance + sal.site_allowance + sal.conveyance_allowance) if sal else Decimal("0.00")
            ot_pay = ts_cost if (detail and detail.employment_type in (EmployeeDetail.EmploymentType.DAILY_WAGE, EmployeeDetail.EmploymentType.SKILLED_LABOR, EmployeeDetail.EmploymentType.UNSKILLED_LABOR)) else Decimal("0.00")
            if ot_pay > 0:
                basic = Decimal("0.00")
                allow = Decimal("0.00")
            gross = (basic + allow + ot_pay).quantize(Decimal("0.01"))
            if gross <= 0:
                continue

            stat = NepalPayrollEngine.compute_monthly_statutory(
                basic_pay=basic,
                gross_pay=gross,
                pf_enrolled=detail.pf_enrolled if detail else False,
                ssf_enrolled=detail.ssf_enrolled if detail else False,
                is_married=detail.is_married_tax if detail else False,
                rule_set=run.statutory_rule_set,
            )

            adv_rec = AdvanceRecord.objects.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.filter(company=run.company, employee=emp, status=StaffLoan.Status.ACTIVE).first()

            rem_cash = gross - stat["pf_ssf"] - stat["tds_tax"]
            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"), gross - stat["pf_ssf"] - stat["tds_tax"] - adv_ded - loan_ded).quantize(Decimal("0.01"))
            ded = (stat["pf_ssf"] + stat["tds_tax"] + adv_ded + loan_ded).quantize(Decimal("0.01"))
            tot_gross += gross
            tot_ded += ded
            tot_net += net

            PayrollLine.objects.create(
                payroll_run=run,
                employee=emp,
                project=emp.project or run.project,
                basic_pay=basic,
                allowances=allow,
                overtime_pay=ot_pay,
                gross_pay=gross,
                pf_ssf_deduction=stat["pf_ssf"],
                tds_tax=stat["tds_tax"],
                advance_recovery=adv_ded,
                loan_deduction=loan_ded,
                net_pay=net,
                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.status = PayrollRun.Status.CALCULATED
        run.save(update_fields=["total_gross", "total_deductions", "total_net_pay", "status"])
        return run

    @staticmethod
    @transaction.atomic
    def approve_payroll(*, run: PayrollRun, user) -> PayrollRun:
        run = PayrollRun.objects.select_for_update().get(pk=run.pk)
        if run.created_by_id == user.id and not user.is_superuser:
            raise ValidationError("Maker-checker: payroll creator cannot approve payroll run.")
        run.status = PayrollRun.Status.APPROVED
        run.approved_by = user
        run.save(update_fields=["status", "approved_by"])
        return run

    @staticmethod
    @transaction.atomic
    def post_payroll_to_gl(*, run: PayrollRun, user) -> PayrollRun:
        run = PayrollRun.objects.select_for_update().get(pk=run.pk)
        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 = _find_acc(run.company, Account.ControlRole.DIRECT_EXPENSES, "5020")
        wage_acc = _find_acc(run.company, Account.ControlRole.WAGES_PAYABLE, "2035")
        pf_acc = _find_acc(run.company, Account.ControlRole.PF_SSF_PAYABLE, "2045")
        tds_acc = _find_acc(run.company, Account.ControlRole.TDS_PAYABLE, "2120")
        adv_acc = _find_acc(run.company, Account.ControlRole.EMPLOYEE_ADVANCE, "1170")
        loan_acc = _find_acc(run.company, Account.ControlRole.STAFF_LOAN_RECEIVABLE, "1175")
        if not exp_acc or not wage_acc:
            raise ValidationError("Labor Expense (5020) and Wages Payable (2035) accounts are required.")

        gl_lines = []
        tot_pf = 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 Labor Cost: {emp.full_name} ({run.period_label})",
            })
            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_pf += pl.pf_ssf_deduction
            tot_tds += pl.tds_tax

        if tot_pf > 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_pf, "project": run.project, "description": f"PF / SSF 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, "project": run.project, "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"Payroll Accrual {run.run_no} — {run.period_label}",
                "gross_amount": run.total_gross,
                "tds_amount": tot_tds,
                "net_amount": run.total_net_pay,
                "is_control_override": True,
                "override_reason": "System Payroll Run Multi-Employee 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}"},
            )

        Timesheet.objects.filter(
            company=run.company, status=Timesheet.Status.APPROVED,
            period_start__gte=run.period_start, period_end__lte=run.period_end,
        ).update(status=Timesheet.Status.POSTED_TO_PAYROLL)

        run.accrual_voucher = v
        run.status = PayrollRun.Status.POSTED
        run.save(update_fields=["accrual_voucher", "status"])
        record_audit_event(
            company=run.company, actor=user, action="PAYROLL_POSTED", entity_type="PayrollRun",
            entity_id=str(run.id), new_state={"run_no": run.run_no, "voucher": v.voucher_no},
        )
        return run


from .attendance_leave_overtime import AttendanceEngine, ConstructionLabourEngine, LeaveEngine, OvertimeEngine  # noqa: E402,F401
from .formula_engine import SafeSalaryFormulaEngine  # noqa: E402,F401
from .payroll_enterprise import (  # noqa: E402,F401
    EmployeeLifecycleAndSettlementEngine,
    PayrollAccountingAndPaymentEngine,
    PayrollProrationAndTaxEngine,
)
from .payslip_and_reports import (  # noqa: E402,F401
    HRReportCatalogService,
    HrConfigService,
    HrDashboardService,
    PayslipPrintStudioService,
)
