import csv
import io
from datetime import date
from decimal import Decimal
from django.db.models import Count, Sum
from django.http import HttpResponse
import xlsxwriter
from weasyprint import HTML

from apps.accounting.models import AdvanceRecord, EmployeeProfile, StaffLoan
from .models import (
    AttendanceCorrection,
    AttendanceRecord,
    DailyWageEntry,
    EmployeeDetail,
    EmployeeReimbursement,
    FestivalExpenseRecord,
    FinalSettlement,
    HrConfiguration,
    LeaveBalance,
    LeaveRequest,
    OvertimeRecord,
    PayrollCostAllocation,
    PayrollLine,
    PayrollRun,
    PayrollStatutoryRuleSet,
    Payslip,
    PieceRateWorkRecord,
    SalaryRevision,
)


def mask_sensitive_value(val: str) -> str:
    s = str(val or "").strip()
    if len(s) <= 4:
        return "****" if s else "-"
    return ("*" * (len(s) - 4)) + s[-4:]


class HrDashboardService:
    @staticmethod
    def get_summary(company) -> dict:
        today = date.today()
        month_start = today.replace(day=1)
        emp_det = EmployeeDetail.objects.filter(company=company)
        emp_prof = EmployeeProfile.objects.filter(company=company)
        runs = PayrollRun.objects.filter(company=company)
        att_today = AttendanceRecord.objects.filter(company=company, attendance_date=today)

        kpis_employee = {
            "total_employees": emp_prof.count(),
            "active_employees": emp_det.filter(status=EmployeeDetail.Status.ACTIVE).count(),
            "permanent_employees": emp_det.filter(employment_category="PERMANENT").count(),
            "contract_employees": emp_det.filter(employment_category="FIXED_TERM").count(),
            "temporary_employees": emp_det.filter(employment_category="TEMPORARY").count(),
            "daily_wage_employees": emp_det.filter(employment_category="DAILY_WAGE").count(),
            "probation_employees": emp_det.filter(employment_category="PROBATION").count(),
            "part_time_employees": emp_det.filter(employment_category="PART_TIME").count(),
            "on_leave_employees": emp_det.filter(status=EmployeeDetail.Status.ON_LEAVE).count(),
            "resigned_employees": emp_det.filter(status__in=[EmployeeDetail.Status.RESIGNED, EmployeeDetail.Status.TERMINATED]).count(),
            "joined_this_month": emp_det.filter(joining_date__gte=month_start).count(),
            "leaving_this_month": emp_det.filter(exit_date__gte=month_start).count(),
        }

        latest_run = runs.order_by("-pay_date").first()
        kpis_payroll = {
            "monthly_basic_salary": str(emp_prof.filter(is_active=True).aggregate(s=Sum("basic_salary"))["s"] or Decimal("0.00")),
            "total_gross_earnings": str(latest_run.total_gross if latest_run else Decimal("0.00")),
            "total_employee_deductions": str(latest_run.total_deductions if latest_run else Decimal("0.00")),
            "net_salary_payable": str(latest_run.total_net_pay if latest_run else Decimal("0.00")),
            "employer_contributions": str(latest_run.employer_contribution_total if latest_run else Decimal("0.00")),
            "total_employer_cost": str((latest_run.total_gross + latest_run.employer_contribution_total) if latest_run else Decimal("0.00")),
            "runs_calculated": runs.filter(status=PayrollRun.Status.CALCULATED).count(),
            "runs_pending_approval": runs.filter(status__in=[PayrollRun.Status.CALCULATED, PayrollRun.Status.SUBMITTED]).count(),
            "runs_posted": runs.filter(status=PayrollRun.Status.POSTED).count(),
            "salary_payment_pending": str(runs.filter(status=PayrollRun.Status.POSTED).aggregate(s=Sum("total_net_pay"))["s"] or Decimal("0.00")),
        }

        kpis_attendance = {
            "present_today": att_today.filter(status=AttendanceRecord.Status.PRESENT).count(),
            "absent_today": att_today.filter(status=AttendanceRecord.Status.ABSENT).count(),
            "late_arrivals": att_today.filter(late_minutes__gt=0).count(),
            "early_departures": att_today.filter(early_departure_minutes__gt=0).count(),
            "overtime_hours_month": str(OvertimeRecord.objects.filter(company=company, ot_date__gte=month_start).aggregate(s=Sum("approved_ot_hours"))["s"] or Decimal("0.00")),
            "approved_leave_today": LeaveRequest.objects.filter(company=company, status="APPROVED", start_date__lte=today, end_date__gte=today).count(),
            "pending_corrections": AttendanceCorrection.objects.filter(company=company, status="PENDING").count(),
            "pending_overtime": OvertimeRecord.objects.filter(company=company, status="PENDING").count(),
        }

        kpis_construction = {
            "office_staff": emp_det.filter(assigned_project__isnull=True, status=EmployeeDetail.Status.ACTIVE).count(),
            "project_staff": emp_det.filter(assigned_project__isnull=False, status=EmployeeDetail.Status.ACTIVE).count(),
            "daily_wage_cost_month": str(DailyWageEntry.objects.filter(company=company, work_date__gte=month_start).aggregate(s=Sum("net_payable"))["s"] or Decimal("0.00")),
            "piece_rate_cost_month": str(PieceRateWorkRecord.objects.filter(company=company, work_date__gte=month_start).aggregate(s=Sum("total_amount"))["s"] or Decimal("0.00")),
            "project_wip_allocated": str(PayrollCostAllocation.objects.filter(company=company, is_wip=True).aggregate(s=Sum("allocated_amount"))["s"] or Decimal("0.00")),
        }

        charts = {
            "monthly_payroll_trend": [
                {"period": r.period_label, "gross": float(r.total_gross), "net": float(r.total_net_pay)}
                for r in runs.order_by("pay_date")[:12]
            ],
            "department_payroll": [
                {"department": row["employee__department__name"] or "Unassigned", "gross": float(row["g"] or 0)}
                for row in PayrollLine.objects.filter(payroll_run__company=company).values("employee__department__name").annotate(g=Sum("gross_pay"))
            ],
            "project_labour_cost": [
                {"project": row["project__name"] or "Overhead", "amount": float(row["t"] or 0)}
                for row in PayrollCostAllocation.objects.filter(company=company).values("project__name").annotate(t=Sum("allocated_amount"))
            ],
            "employment_mix": [
                {"category": row["employment_category"], "count": row["c"]}
                for row in emp_det.values("employment_category").annotate(c=Count("id"))
            ],
        }
        return {
            "kpis_employee": kpis_employee,
            "kpis_payroll": kpis_payroll,
            "kpis_attendance": kpis_attendance,
            "kpis_construction": kpis_construction,
            "charts": charts,
        }


class PayslipPrintStudioService:
    """Multi-format A4/A5 Nepal PDF payslip studio with confidentiality masking."""

    FORMATS = ["STANDARD", "COMPACT", "DETAILED", "SITE_WORKER", "DAILY_SLIP", "HOURLY_SLIP", "MANAGEMENT_SHEET"]

    @staticmethod
    def render_pdf(*, payslip: Payslip, template_format: str = "STANDARD", page_size: str = "A4") -> HttpResponse:
        pl = payslip.payroll_line
        run = pl.payroll_run
        emp = pl.employee
        detail = getattr(emp, "hr_detail", None)
        fmt = template_format.upper() if template_format else "STANDARD"
        ps = "A5" if str(page_size).upper() == "A5" else "A4"

        bank_mask = mask_sensitive_value(detail.bank_account_no if detail else "")
        pan_mask = mask_sensitive_value(detail.pan_no if detail else "")

        html = f"""
        <html><head><style>
          @page {{ size: {ps} portrait; margin: 10mm; }}
          body {{ font-family: sans-serif; font-size: 10px; color: #0f172a; }}
          .hdr {{ border-bottom: 2px solid #0f172a; padding-bottom: 6px; margin-bottom: 8px; display: flex; justify-content: space-between; }}
          h2 {{ margin: 0; font-size: 14px; }}
          table {{ width: 100%; border-collapse: collapse; margin-top: 6px; }}
          th, td {{ border: 1px solid #cbd5e1; padding: 4px 6px; text-align: left; }}
          th {{ background: #f1f5f9; }}
          .num {{ text-align: right; font-family: monospace; }}
          .tot {{ font-weight: bold; background: #e2e8f0; }}
        </style></head><body>
          <div class='hdr'>
            <div><h2>{run.company.name}</h2><div>Payslip ({fmt}) — {run.period_label} (Pay Date: {run.pay_date} / {run.bs_pay_date})</div></div>
            <div><b>No:</b> {payslip.payslip_no}<br/><b>Status:</b> {run.status}</div>
          </div>
          <table>
            <tr><th>Employee</th><td>{emp.full_name} ({emp.employee_code})</td><th>Designation</th><td>{emp.designation}</td></tr>
            <tr><th>Department</th><td>{emp.department.name if emp.department else '-'}</td><th>Project</th><td>{pl.project.name if pl.project else 'Head Office'}</td></tr>
            <tr><th>Bank Account</th><td>{detail.bank_name if detail else '-'} ({bank_mask})</td><th>PAN (Masked)</th><td>{pan_mask}</td></tr>
          </table>
          <table>
            <thead><tr><th>Earnings</th><th class='num'>Amount</th><th>Deductions</th><th class='num'>Amount</th></tr></thead>
            <tbody>
              <tr><td>Basic Salary ({pl.payable_days}/{pl.total_period_days}d)</td><td class='num'>{pl.basic_pay}</td><td>Employee PF / SSF</td><td class='num'>{pl.pf_ssf_deduction}</td></tr>
              <tr><td>Allowances</td><td class='num'>{pl.allowances}</td><td>Income Tax (TDS)</td><td class='num'>{pl.tds_tax}</td></tr>
              <tr><td>Overtime &amp; Piece/Wage Pay</td><td class='num'>{pl.overtime_pay}</td><td>Advance Recovery</td><td class='num'>{pl.advance_recovery}</td></tr>
              <tr><td>Festival / Bonus</td><td class='num'>{pl.bonus_festival}</td><td>Staff Loan Installment</td><td class='num'>{pl.loan_deduction}</td></tr>
              <tr><td>Reimbursements (Non-Taxable Claim)</td><td class='num'>{pl.reimbursements}</td><td>Other Deductions</td><td class='num'>{pl.other_deductions}</td></tr>
              <tr class='tot'><td>Gross Pay</td><td class='num'>{pl.gross_pay}</td><td>Total Deductions</td><td class='num'>{pl.pf_ssf_deduction + pl.tds_tax + pl.advance_recovery + pl.loan_deduction + pl.other_deductions}</td></tr>
            </tbody>
          </table>
          <table>
            <tr><th>Net Salary Payable</th><td class='num'><b>{run.company.base_currency} {pl.net_pay}</b></td><th>Employer SSF / PF / Gratuity</th><td class='num'>{pl.employer_ssf + pl.employer_pf + pl.gratuity_accrual} (Total Employer Cost: {pl.employer_total_cost})</td></tr>
          </table>
        </body></html>
        """
        pdf_bytes = HTML(string=html).write_pdf()
        resp = HttpResponse(pdf_bytes, content_type="application/pdf")
        resp["Content-Disposition"] = f'attachment; filename="{payslip.payslip_no}.pdf"'
        return resp


class HRReportCatalogService:
    """8-Category HR, Payroll, Tax, SSF & Project Labour Report Library with PDF / Excel / CSV exports."""

    CATALOG = [
        {"code": "A_EMPLOYEE_REGISTER", "category": "A_EMPLOYEE", "title": "Employee Master & Category Register"},
        {"code": "B_PAYROLL_REGISTER", "category": "B_PAYROLL", "title": "Monthly Salary & Payroll Sheet"},
        {"code": "C_ATTENDANCE_SUMMARY", "category": "C_ATTENDANCE", "title": "Attendance & Biometric Log Summary"},
        {"code": "D_OVERTIME_REGISTER", "category": "D_OVERTIME", "title": "Overtime & Labour Cap Exception Register"},
        {"code": "E_LEAVE_BALANCE", "category": "E_LEAVE", "title": "Employee Leave Balances & Utilization"},
        {"code": "F_TAX_SSF_REGISTER", "category": "F_TAX_SSF", "title": "TDS Tax & SSF/PF Remittance Statement"},
        {"code": "G_PROJECT_LABOUR", "category": "G_PROJECT_LABOUR", "title": "Project & Worksite Labour WIP Cost Report"},
        {"code": "H_BENEFITS_SETTLEMENT", "category": "H_BENEFITS_SETTLEMENT", "title": "Advances, Loans & Final Exit Settlements"},
    ]

    @staticmethod
    def run_report(*, company, code: str, can_view_sensitive: bool) -> dict:
        c = code.upper()
        if c == "A_EMPLOYEE_REGISTER":
            cols = ["Code", "Name", "Category", "Designation", "Department", "Project", "PAN", "Basic"]
            rows = []
            for e in EmployeeProfile.objects.filter(company=company).select_related("department", "project", "hr_detail"):
                d = getattr(e, "hr_detail", None)
                rows.append([
                    e.employee_code, e.full_name, d.employment_category if d else "-", e.designation,
                    e.department.name if e.department else "-", e.project.name if e.project else "-",
                    (d.pan_no if (d and can_view_sensitive) else mask_sensitive_value(d.pan_no if d else "")),
                    str(e.basic_salary) if can_view_sensitive else "***",
                ])
            return {"code": c, "title": "Employee Master Register", "columns": cols, "rows": rows}

        if c in ("B_PAYROLL_REGISTER", "F_TAX_SSF_REGISTER"):
            if not can_view_sensitive:
                raise PermissionError("Missing hr.payroll_sensitive permission for confidential payroll report.")
            cols = ["Run No", "Employee", "Basic", "OT/Wage", "Gross", "Emp PF/SSF", "TDS Tax", "Net Pay", "Employer Cost"]
            rows = [
                [l.payroll_run.run_no, l.employee.full_name, str(l.basic_pay), str(l.overtime_pay), str(l.gross_pay), str(l.pf_ssf_deduction), str(l.tds_tax), str(l.net_pay), str(l.employer_total_cost)]
                for l in PayrollLine.objects.filter(payroll_run__company=company).select_related("payroll_run", "employee")[:300]
            ]
            return {"code": c, "title": "Payroll & Statutory Register", "columns": cols, "rows": rows}

        if c == "C_ATTENDANCE_SUMMARY":
            cols = ["Date", "Employee", "Status", "In", "Out", "Worked Hrs", "Late Min", "Source"]
            rows = [
                [str(a.attendance_date), a.employee.full_name, a.status, str(a.check_in or "-"), str(a.check_out or "-"), str(a.actual_working_hours), str(a.late_minutes), a.source]
                for a in AttendanceRecord.objects.filter(company=company).select_related("employee")[:300]
            ]
            return {"code": c, "title": "Attendance Log Summary", "columns": cols, "rows": rows}

        if c == "D_OVERTIME_REGISTER":
            cols = ["Date", "Employee", "Category", "Actual Hrs", "Approved Hrs", "Mult", "Amount", "Cap Alert", "Status"]
            rows = [
                [str(o.ot_date), o.employee.full_name, o.ot_category, str(o.actual_ot_hours), str(o.approved_ot_hours), str(o.multiplier), str(o.calculated_amount), "YES" if o.exceeds_statutory_cap else "NO", o.status]
                for o in OvertimeRecord.objects.filter(company=company).select_related("employee")[:300]
            ]
            return {"code": c, "title": "Overtime & Cap Register", "columns": cols, "rows": rows}

        if c == "E_LEAVE_BALANCE":
            cols = ["Employee", "Type", "FY", "Opening", "Accrued", "Taken", "Available"]
            rows = []
            for lb in LeaveBalance.objects.filter(company=company).select_related("employee")[:300]:
                avail = lb.opening_balance + lb.accrued_days + lb.adjusted_days - lb.taken_days - lb.encashed_days
                rows.append([lb.employee.full_name, lb.leave_type_code, lb.fiscal_year_label, str(lb.opening_balance), str(lb.accrued_days), str(lb.taken_days), str(avail)])
            return {"code": c, "title": "Leave Balances", "columns": cols, "rows": rows}

        if c == "G_PROJECT_LABOUR":
            cols = ["Run", "Employee", "Project", "Allocation %", "Allocated Cost", "WIP"]
            rows = [
                [a.payroll_run.run_no, a.employee.full_name, a.project.name if a.project else "-", str(a.allocation_pct), str(a.allocated_amount), "YES" if a.is_wip else "NO"]
                for a in PayrollCostAllocation.objects.filter(company=company).select_related("payroll_run", "employee", "project")[:300]
            ]
            return {"code": c, "title": "Project Labour WIP Cost", "columns": cols, "rows": rows}

        cols = ["Employee", "Exit Type", "Last Date", "Leave Enc.", "Gratuity", "Adv+Loan Recovery", "Net Payable", "Status"]
        rows = [
            [s.employee.full_name, s.exit_type, str(s.last_working_date), str(s.leave_encashment), str(s.gratuity_settlement), str(s.advance_recovery + s.loan_recovery), str(s.net_payable), s.status]
            for s in FinalSettlement.objects.filter(company=company).select_related("employee")[:200]
        ]
        return {"code": c, "title": "Benefits & Final Settlements", "columns": cols, "rows": rows}

    @staticmethod
    def export_report(*, company, code: str, file_format: str, can_view_sensitive: bool) -> HttpResponse:
        res = HRReportCatalogService.run_report(company=company, code=code, can_view_sensitive=can_view_sensitive)
        fmt = file_format.lower()
        if fmt == "pdf":
            th = "".join(f"<th>{c}</th>" for c in res["columns"])
            tr = "".join("<tr>" + "".join(f"<td>{v}</td>" for v in r) + "</tr>" for r in res["rows"])
            html = f"<html><body style='font-family:sans-serif;font-size:9px;'><h2>{company.name} — {res['title']}</h2><table border='1' cellspacing='0' cellpadding='4' width='100%'><thead><tr>{th}</tr></thead><tbody>{tr}</tbody></table></body></html>"
            pdf_bytes = HTML(string=html).write_pdf()
            resp = HttpResponse(pdf_bytes, content_type="application/pdf")
            resp["Content-Disposition"] = f'attachment; filename="{code.lower()}.pdf"'
            return resp
        if fmt in ("xlsx", "excel"):
            buf = io.BytesIO()
            wb = xlsxwriter.Workbook(buf, {"in_memory": True})
            ws = wb.add_worksheet("HR_Report")
            for idx, col in enumerate(res["columns"]):
                ws.write(0, idx, col)
            for r_idx, row in enumerate(res["rows"], start=1):
                ws.write_row(r_idx, 0, row)
            wb.close()
            resp = HttpResponse(buf.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            resp["Content-Disposition"] = f'attachment; filename="{code.lower()}.xlsx"'
            return resp
        buf = io.StringIO()
        w = csv.writer(buf)
        w.writerow(res["columns"])
        w.writerows(res["rows"])
        resp = HttpResponse(buf.getvalue(), content_type="text/csv")
        resp["Content-Disposition"] = f'attachment; filename="{code.lower()}.csv"'
        return resp


class HrConfigService:
    @staticmethod
    def get_or_create_config(company) -> HrConfiguration:
        cfg, _ = HrConfiguration.objects.get_or_create(
            company=company,
            defaults={
                "gl_mappings": {
                    "basic_salary_expense": "5020",
                    "employer_contribution_expense": "5025",
                    "salary_payable": "2035",
                    "pf_ssf_payable": "2045",
                    "gratuity_payable": "2048",
                    "tds_payable": "2120",
                    "employee_advance": "1170",
                    "staff_loan_receivable": "1175",
                    "project_labour_wip": "1360",
                    "salary_allocation_clearing": "5029",
                }
            },
        )
        return cfg

