# ============================================================
# ADDITIVE: Payroll Calculation Engine
# ------------------------------------------------------------
# This file is new - it does not replace or remove anything
# that already exists in Company/ or Employee/. It implements
# the payroll policy exactly as specified:
#
#   - Present Day        -> full per-day salary
#   - Half Day            -> 50% of per-day salary; any hours worked
#                            beyond half of the expected work hours
#                            are paid separately as "extra hour pay"
#   - Overtime             -> hours worked beyond the expected work
#                            hours on a normal working day, paid at
#                            the employee's Overtime_Rate
#   - Sunday               -> always a fully paid day. If the
#                            employee works, ALL hours worked that
#                            day are paid as overtime.
#   - Saturday (OFF)       -> full salary given. If the employee
#                            works, ALL hours worked are overtime.
#   - Saturday (HALF)      -> full salary if the employee works a
#                            half day; hours beyond the half-day
#                            mark are paid as overtime.
#   - Saturday (FULL)      -> treated exactly like a normal weekday.
#   - Holiday / Paid Leave / Sick Leave / Casual Leave
#                           -> fully paid day. If the employee still
#                            logs hours, they are all paid as
#                            overtime.
#   - PF / TDS / ESI       -> each is a percentage of GROSS salary
#                            (not of basic salary).
#   - Gross Salary  = Full Day Salary + Half Day Salary
#                     + Overtime Pay + Extra Hour Pay
#   - Net Salary    = Gross Salary - (PF + TDS + ESI deductions)
#
# Only PAST/COMPLETED days are ever calculated (today itself and
# any future day are skipped), and a payroll row already marked
# "Paid" is never recalculated/overwritten.
# ============================================================

from calendar import monthrange
from datetime import date, datetime, timedelta
from decimal import Decimal

from Employee.models import EmployeeDT, AttendanceEmp, Payroll


LEAVE_TYPES = ("Holiday", "Paid Leave", "Sick Leave", "Casual Leave")


def time_to_decimal(time_str):
    """
    Convert a worked-hours value into decimal hours.
    Supports:
      "HH:MM"
      "HH:MM:SS"
      "HH:MM AM/PM"
      a plain number of hours ("7.5")
    Returns Decimal("0") for anything empty/unparseable.
    """
    if not time_str:
        return Decimal("0")

    time_str = str(time_str).strip()

    try:
        if "AM" in time_str.upper() or "PM" in time_str.upper():
            t = datetime.strptime(time_str, "%I:%M %p")
            return Decimal(t.hour) + Decimal(t.minute) / Decimal(60)

        if ":" in time_str:
            parts = time_str.split(":")
            hours = int(parts[0])
            minutes = int(parts[1]) if len(parts) > 1 else 0
            seconds = int(parts[2]) if len(parts) > 2 else 0
            return (
                Decimal(hours)
                + Decimal(minutes) / Decimal(60)
                + Decimal(seconds) / Decimal(3600)
            )

        # plain number of hours, e.g. "7.5"
        return Decimal(time_str)

    except Exception:
        return Decimal("0")


def calculate_salary(employee_id, month, year, company=None):
    """
    Calculate one employee's salary for the given month/year.

    `company`, if passed, is used as a safety check so payroll for
    one company can never be generated using another company's
    employee_code by mistake.

    Returns a dict of computed values, or {"error": "..."} if the
    salary could not be computed.
    """
    try:
        employee = EmployeeDT.objects.get(employee_code=employee_id)
    except EmployeeDT.DoesNotExist:
        return {"error": "Employee Not Found"}

    if company is not None and employee.company_id != company.pk:
        return {"error": "Employee does not belong to this company"}

    if not employee.Date_of_Joining:
        return {"error": "Date of Joining not set for this employee"}

    basic_salary = employee.Basic_Salary or Decimal("0")
    pf_percentage = employee.PF_Percentage or Decimal("0")
    tds_percentage = employee.TDS_Percentage or Decimal("0")
    esi_percentage = employee.ESI_Percentage or Decimal("0")
    overtime_rate = employee.Overtime_Rate or Decimal("0")
    expected_work_hours = Decimal(employee.Work_hours or 8)

    total_days = monthrange(year, month)[1]
    first_day = date(year, month, 1)
    last_day = date(year, month, total_days)

    joining_date = employee.Date_of_Joining

    if joining_date > last_day:
        return {
            "Employee Name": employee.name,
            "Basic Salary": basic_salary,
            "Month Days": total_days,
            "Net Salary": Decimal("0.00"),
            "message": "Employee joined after this payroll month",
        }

    start_date = max(first_day, joining_date)
    # Only completed days are payable - never today or a future day.
    end_date = min(last_day, date.today() - timedelta(days=1))

    if end_date < start_date:
        return {
            "Employee Name": employee.name,
            "Basic Salary": basic_salary,
            "Month Days": total_days,
            "Net Salary": Decimal("0.00"),
            "message": "No completed days to process yet for this month",
        }

    per_day_salary = basic_salary / Decimal(total_days)
    extra_hr_rate = (
        per_day_salary / expected_work_hours
        if expected_work_hours
        else Decimal("0")
    )

    attendance_records = AttendanceEmp.objects.filter(
        Employee_ID=employee_id,
        date__gte=start_date,
        date__lte=end_date,
    )
    attendance_map = {a.date: a for a in attendance_records}

    present_days = 0
    half_days = 0
    overtime_hours = Decimal("0")
    extra_hr = Decimal("0")
    total_working_hr = Decimal("0")

    day = start_date
    while day <= end_date:
        weekday = day.weekday()  # Monday = 0 ... Sunday = 6
        record = attendance_map.get(day)

        if not record:
            # No attendance row at all for this day -> Absent, no pay.
            day += timedelta(days=1)
            continue

        work_hours = time_to_decimal(record.total_working_hours)
        if record.status == "Present" and not work_hours:
            work_hours = expected_work_hours

        # ---------------- Sunday: always paid ----------------
        if weekday == 6:
            present_days += 1
            if work_hours:
                overtime_hours += work_hours
            total_working_hr += work_hours if work_hours else expected_work_hours
            day += timedelta(days=1)
            continue

        # ---------------- Saturday ----------------
        if weekday == 5:
            saturday_policy = employee.saturday_policy or "FULL"

            if saturday_policy == "OFF":
                present_days += 1
                if work_hours:
                    overtime_hours += work_hours
                total_working_hr += (
                    work_hours if work_hours else expected_work_hours
                )
                day += timedelta(days=1)
                continue

            if saturday_policy == "HALF":
                half_expected = expected_work_hours / Decimal(2)

                if record.status == "Absent":
                    day += timedelta(days=1)
                    continue

                if record.status in LEAVE_TYPES:
                    present_days += 1
                    if work_hours:
                        overtime_hours += work_hours
                    total_working_hr += (
                        work_hours if work_hours else expected_work_hours
                    )
                    day += timedelta(days=1)
                    continue

                # Worked (fully or partly) on a HALF-policy Saturday:
                # full salary for the day, anything beyond the half-day
                # mark is overtime.
                present_days += 1
                overtime_hours += max(work_hours - half_expected, Decimal("0"))
                total_working_hr += work_hours
                day += timedelta(days=1)
                continue

            # saturday_policy == "FULL" -> falls through and is treated
            # exactly like a normal weekday below.

        # ---------------- Holiday / Paid / Sick / Casual Leave ----------------
        if record.status in LEAVE_TYPES:
            present_days += 1
            if work_hours:
                overtime_hours += work_hours
            total_working_hr += work_hours if work_hours else expected_work_hours
            day += timedelta(days=1)
            continue

        if record.status == "Absent":
            day += timedelta(days=1)
            continue

        # ---------------- Normal weekday (and FULL-policy Saturday) ----------------
        if work_hours >= expected_work_hours:
            present_days += 1
            overtime_hours += work_hours - expected_work_hours
        elif work_hours >= expected_work_hours / Decimal(2):
            half_days += 1
            extra_hr += work_hours - (expected_work_hours / Decimal(2))
        # else: worked less than half day -> Absent, no pay

        total_working_hr += work_hours
        day += timedelta(days=1)

    # ---------------- Salary calculation ----------------
    full_day_salary = per_day_salary * present_days
    half_day_salary = (per_day_salary / Decimal(2)) * half_days
    overtime_pay = overtime_hours * overtime_rate
    extra_hr_pay = extra_hr * extra_hr_rate

    gross_salary = full_day_salary + half_day_salary + overtime_pay + extra_hr_pay

    # PF / TDS / ESI are each a percentage of GROSS salary.
    pf_deduction = (pf_percentage / Decimal("100")) * gross_salary
    tds_deduction = (tds_percentage / Decimal("100")) * gross_salary
    esi_deduction = (esi_percentage / Decimal("100")) * gross_salary

    # ============================================================
    # INSURANCE PREMIUM DEDUCTION
    # ============================================================

    insurance_deduction = Decimal("0.00")

    try:
        from Insurance.models import EmployeeInsurancePolicy

        insurance_policy = (
            EmployeeInsurancePolicy.objects
            .filter(
                employee=employee,
                company=employee.company,
                status="ACTIVE",
                start_date__lte=last_day,
                end_date__gte=first_day,
            )
            .order_by("-start_date")
            .first()
        )

        if insurance_policy:
            insurance_deduction = (
                insurance_policy.employee_monthly_premium
                or Decimal("0.00")
            )

    except Exception:
        # Insurance must never break payroll generation.
        insurance_deduction = Decimal("0.00")
    total_deductions = pf_deduction + tds_deduction + esi_deduction + insurance_deduction

    net_salary = gross_salary - total_deductions

    return {
        "Employee Name": employee.name,
        "Basic Salary": basic_salary,
        "Month Days": total_days,
        "Total Present Days": present_days,
        "Total Half Days": half_days,
        "Overtime Hours": overtime_hours,
        "Full Day Salary": full_day_salary,
        "Half Day Salary": half_day_salary,
        "Overtime Pay": overtime_pay,
        "Extra Hour Pay": extra_hr_pay,
        "Gross Salary": gross_salary,
        "Total Deductions": total_deductions,
        "Net Salary": net_salary,
        "total_working_hr": total_working_hr,
        "Start Date": start_date,
        "End Date": end_date,
        "pf_deduction": pf_deduction,
        "tds_deduction": tds_deduction,
        "esi_deduction": esi_deduction,
        "insurance_deduction": insurance_deduction,
    }
    

def generate_monthly_payroll(month, year, company):
    """
    Generate/update Payroll rows for every active employee of
    `company` for the given month/year.

    Rules:
      - A Payroll row already marked "Paid" is NEVER recalculated
        or overwritten - it is returned as-is.
      - Every other row (missing, or "Unpaid") is (re)calculated
        and saved.

    Returns:
        {
          "payrolls": [Payroll, ...],
          "skipped_paid": <int>,
          "errors": [{"employee_id": ..., "name": ..., "error": ...}, ...],
        }
    """
    employees = EmployeeDT.objects.filter(company=company, is_active=True)

    payrolls = []
    skipped_paid = 0
    errors = []

    for employee in employees:
        salary_data = calculate_salary(
            employee.employee_code, month, year, company=company
        )

        if "error" in salary_data:
            errors.append({
                "employee_id": employee.employee_code,
                "name": employee.name,
                "error": salary_data["error"],
            })
            continue

        existing = Payroll.objects.filter(
            Employee_ID=employee.employee_code,
            month=month,
            year=year,
            company=company,
        ).first()

        if existing and existing.status == "Paid":
            skipped_paid += 1
            payrolls.append(existing)
            continue

        defaults = {
            "name": employee.name,
            "company": company,
            "basic_salary": salary_data.get("Basic Salary") or Decimal("0"),
            "present_days": salary_data.get("Total Present Days") or 0,
            "half_days": salary_data.get("Total Half Days") or 0,
            "overtime_hours": salary_data.get("Overtime Hours") or Decimal("0"),
            "full_day_salary": salary_data.get("Full Day Salary") or Decimal("0"),
            "half_day_salary": salary_data.get("Half Day Salary") or Decimal("0"),
            "overtime_pay": salary_data.get("Overtime Pay") or Decimal("0"),
            "gross_salary": salary_data.get("Gross Salary") or Decimal("0"),
            "total_deductions": salary_data.get("Total Deductions") or Decimal("0"),
            "net_salary": salary_data.get("Net Salary") or Decimal("0"),
            "total_working_hr": salary_data.get("total_working_hr") or Decimal("0"),
            "PF_deduction": salary_data.get("pf_deduction") or Decimal("0"),
            "TDS_deduction": salary_data.get("tds_deduction") or Decimal("0"),
            "ESI_deduction": salary_data.get("esi_deduction") or Decimal("0"),
            "insurance_deduction": (salary_data.get("insurance_deduction")or Decimal("0")),
        }

        if "message" in salary_data:
            # Joined-after-month / no-completed-days case: create a
            # zeroed row instead of silently skipping the employee.
            defaults.update({
                "present_days": 0,
                "half_days": 0,
                "overtime_hours": Decimal("0"),
                "full_day_salary": Decimal("0"),
                "half_day_salary": Decimal("0"),
                "overtime_pay": Decimal("0"),
                "gross_salary": Decimal("0"),
                "total_deductions": Decimal("0"),
                "net_salary": Decimal("0"),
                "total_working_hr": Decimal("0"),
                "PF_deduction": Decimal("0"),
                "TDS_deduction": Decimal("0"),
                "ESI_deduction": Decimal("0"),
            })

        if existing:
            for key, value in defaults.items():
                setattr(existing, key, value)
            existing.save()
            payrolls.append(existing)
        else:
            obj = Payroll.objects.create(
                Employee_ID=employee.employee_code,
                month=month,
                year=year,
                **defaults,
            )
            payrolls.append(obj)

    return {
        "payrolls": payrolls,
        "skipped_paid": skipped_paid,
        "errors": errors,
    }
    