# ============================================================
# Timesheet - shared helpers (reuses People.common: envelope, paging, parsing, CrudBase)
# ============================================================
import calendar
from datetime import timedelta
from decimal import Decimal

from django.db.models import Q, Sum
from django.utils import timezone
from rest_framework.permissions import BasePermission

from Employee.employee_crud_permissions import (_role_is_usable, actor_label, resolve_actor_role, role_allows)  # noqa: F401
from Employee.employee_authentication import EmployeeJWTAuthentication, IsEmployeeAuthenticated  # noqa: F401
from Employee.leave_models import ReportingHierarchy
from People.common import (CrudBase, PeopleAuthMixin, dept_name, emp_brief, emp_by_code, employees_qs, err, iso,  # noqa: F401
                           ok, paginate, to_bool, to_date, to_decimal, to_int, next_seq)  # noqa: F401

from .models import (OvertimeClaim, ProjectAllocation, TimesheetEntry, TimesheetProject, TimesheetSetting)

MODULE = "timesheet"
Q2 = Decimal("0.01")
OPEN_PROJECT = ("Planning", "Active")          # statuses that accept new hours


# ---------------------------------------------------------------
# permissions: Company Admin always. Employee/HR: can_<action>_timesheet if that checkbox exists,
# otherwise the same action on the "attendance" module (existing HR roles work without a new migration).
# ---------------------------------------------------------------
def timesheet_allows(user, action):
    actor = resolve_actor_role(user)
    if actor == "admin":
        return True
    if actor is None:
        return False
    role = _role_is_usable(user)
    if role is None:
        return False
    a = "edit" if action == "approve" else action
    return role_allows(role, MODULE, a) or role_allows(role, "attendance", a)


class IsTimesheetUser(BasePermission):
    message = "You do not have permission to manage Timesheets."
    METHOD_ACTION = {"GET": "view", "HEAD": "view", "OPTIONS": "view", "POST": "create",
                     "PUT": "edit", "PATCH": "edit", "DELETE": "delete"}

    def has_permission(self, request, view):
        act = getattr(view, "permission_action", None)
        if act is None:
            va = getattr(view, "action", None)
            act = {"update_post": "edit", "delete_post": "delete"}.get(va) or \
                  (getattr(view, "permission_action_map", None) or {}).get(va)
        act = act or self.METHOD_ACTION.get(request.method)
        return bool(act) and timesheet_allows(request.user, act)


class TimesheetAuthMixin(PeopleAuthMixin):
    permission_classes = [IsTimesheetUser]


class TimesheetCrud(TimesheetAuthMixin, CrudBase):
    employee_field = "employee__employee_code"

    def filter(self, qs, p):
        emp = p.get("employee")
        qs = super().filter(qs, {k: v for k, v in p.items() if k != "employee"})
        if emp and self.employee_field:
            qs = qs.filter(**{self.employee_field: emp})
        return qs


# ---------------------------------------------------------------
# settings / dates
# ---------------------------------------------------------------
def get_setting(company):
    s, _ = TimesheetSetting.objects.get_or_create(company=company)
    return s


def week_bounds(d, week_start_day=0):
    start = d - timedelta(days=(d.weekday() - week_start_day) % 7)
    return start, start + timedelta(days=6)


def cycle_label(start, end):
    return f"{start.strftime('%d %b')} - {end.strftime('%d %b')}"


def month_range(month, year):
    return (timezone.datetime(year, month, 1).date(), timezone.datetime(year, month, calendar.monthrange(year, month)[1]).date())


def parse_month_year(d, default_today=True):
    t = timezone.localdate()
    month = to_int(d.get("month"), t.month if default_today else None)
    year = to_int(d.get("year"), t.year if default_today else None)
    if month is None or year is None:
        raise ValueError("month and year are required.")
    if not 1 <= month <= 12 or not 2000 <= year <= 2100:
        raise ValueError("Invalid month/year.")
    return month, year


def find_project(company, ref):
    if ref in (None, ""):
        raise ValueError("project is required (id or code).")
    qs = TimesheetProject.objects.filter(company=company, is_active=True)
    p = qs.filter(pk=int(ref)).first() if str(ref).isdigit() else qs.filter(code__iexact=str(ref).strip()).first()
    if p is None:
        raise ValueError(f"Project '{ref}' not found.")
    return p


def resolve_approver(company, emp):
    """Reporting manager first, then HOD. Never the employee himself. None -> HR/Admin approves."""
    h = ReportingHierarchy.objects.filter(company=company, Employee_ID=emp.employee_code, is_active=True).first()
    for code in ((h.manager_code, h.hod_code) if h else ()):
        if code and code != emp.employee_code:
            return code
    return None


def emp_name(company, code):
    if not code:
        return None
    e = employees_qs(company).filter(employee_code=code).first()
    return e.name if e else code


# ---------------------------------------------------------------
# overtime
# ---------------------------------------------------------------
def recalc_day_overtime(company, employee, day, setting=None, force=()):
    """Hours above the standard day = overtime. Spread across the day's non-manual entries (oldest first). Approved entries are frozen unless listed in `force` (the one being created/edited by HR)."""
    setting = setting or get_setting(company)
    if not setting.auto_overtime:
        return
    std = setting.standard_daily_hours
    entries = list(TimesheetEntry.objects.filter(company=company, employee=employee, work_date=day, is_active=True).exclude(status="Rejected").order_by("id"))
    cum = Decimal("0")
    for e in entries:
        before = max(cum - std, Decimal("0"))
        cum += e.hours
        ot = max(cum - std, Decimal("0")) - before
        if not e.ot_manual and (e.status != "Approved" or e.pk in force) and e.overtime_hours != ot:
            e.overtime_hours = ot
            e.save()


def approved_ot_hours(company, employee, month, year):
    a, b = month_range(month, year)
    return TimesheetEntry.objects.filter(company=company, employee=employee, is_active=True, status="Approved",
                                         work_date__gte=a, work_date__lte=b).aggregate(s=Sum("overtime_hours"))["s"] or Decimal("0")


def money(x):
    return Decimal(x).quantize(Q2)


def calc_pay(hours, rate, mult):
    return money(Decimal(hours) * Decimal(rate) * Decimal(mult))


def claim_rate(emp):
    return Decimal(emp.Overtime_Rate or 0)


def fmt_hours(h):
    h = Decimal(h)
    s = f"{h.normalize():f}"
    return s


def inr(x):
    x = Decimal(x)
    return "₹" + (f"{x:,.0f}" if x == x.to_integral() else f"{x:,.2f}")


# ---------------------------------------------------------------
# project aggregates (Project Allocation tab)
# ---------------------------------------------------------------
def project_logged_hours(project):
    return TimesheetEntry.objects.filter(project=project, is_active=True, status__in=["Submitted", "Approved"]) \
        .aggregate(s=Sum("hours"))["s"] or Decimal("0")


def project_fte(project):
    t = timezone.localdate()
    qs = project.allocations.filter(is_active=True).filter(Q(end_date__isnull=True) | Q(end_date__gte=t))
    return Decimal(qs.aggregate(s=Sum("allocation_percent"))["s"] or 0) / Decimal(100), qs.count()


def budget_status(project, logged):
    if project.status == "Completed":
        return "Completed", None
    if project.status == "Cancelled":
        return "Cancelled", None
    if not project.budget_hours:
        return "No Budget", None
    pct = int(round(logged * 100 / project.budget_hours))
    label = "Over Budget" if pct > 100 else "At Risk" if pct >= 90 else "On Budget"
    return f"{label} ({pct}%)", pct


def project_row(p, request=None, brief=False):
    logged = project_logged_hours(p)
    fte, heads = project_fte(p)
    bs, pct = budget_status(p, logged)
    row = {"id": p.id, "code": p.code, "title": p.title,
           "client_department": p.client_department or (p.department.name if p.department_id else None),
           "allocated_fte": float(fte), "allocated_engineers": f"{fte.normalize():f} FTE", "allocated_people": heads,
           "total_logged_hours": float(logged), "total_logged_hrs": f"{int(logged):,} Hrs" if logged == logged.to_integral() else f"{logged:,.1f} Hrs",
           "budget_status": bs, "budget_percent_used": pct, "status": p.status}
    if not brief:
        row.update(description=p.description, budget_hours=float(p.budget_hours) if p.budget_hours is not None else None,
                   start_date=iso(p.start_date), end_date=iso(p.end_date), is_billable=p.is_billable,
                   manager=emp_brief(p.manager, request) if p.manager_id else None,
                   department_id=p.department_id, created_at=iso(p.created_at))
    return row


def allocation_row(a, request=None):
    return {"id": a.id, "project": {"id": a.project_id, "code": a.project.code, "title": a.project.title},
            "employee": emp_brief(a.employee, request), "role": a.role, "allocation_percent": a.allocation_percent,
            "fte": a.allocation_percent / 100, "start_date": iso(a.start_date), "end_date": iso(a.end_date),
            "is_billable": a.is_billable, "created_at": iso(a.created_at)}


def entry_row(e, request=None):
    ot = e.overtime_hours
    return {"id": e.id, "date": iso(e.work_date), "week_start": iso(e.week_start),
            "employee": emp_brief(e.employee, request),
            "project": {"id": e.project_id, "code": e.project.code, "title": e.project.title},
            "task_summary": e.task_summary, "hours": float(e.hours), "hours_label": f"{fmt_hours(e.hours)} Hrs",
            "overtime_hours": float(ot), "overtime_label": f"{fmt_hours(ot)} OT", "is_billable": e.is_billable,
            "status": e.status, "approver_code": e.approver_code, "decided_by": e.decided_by, "decided_at": iso(e.decided_at),
            "decision_remarks": e.decision_remarks, "submitted_at": iso(e.submitted_at), "created_at": iso(e.created_at)}


def claim_row(c, request=None):
    return {"id": c.id, "employee": emp_brief(c.employee, request),
            "employee_label": f"{c.employee.name} ({c.employee.employee_code})",
            "month": c.month, "year": c.year, "month_label": f"{calendar.month_name[c.month]} {c.year}",
            "approved_ot_hours": float(c.approved_hours), "approved_ot_hours_label": f"{fmt_hours(c.approved_hours)} Hrs",
            "hourly_rate": float(c.hourly_rate), "hourly_rate_label": f"{inr(c.hourly_rate)} / Hr", "multiplier": float(c.multiplier),
            "calculated_ot_pay": float(c.calculated_pay), "calculated_ot_pay_label": inr(c.calculated_pay),
            "approving_manager_code": c.approver_code, "approving_manager": emp_name(c.company, c.approver_code),
            "status": c.status, "source": c.source, "remarks": c.remarks, "decided_by": c.decided_by,
            "decided_at": iso(c.decided_at), "decision_remarks": c.decision_remarks,
            "passed_to_payroll_at": iso(c.passed_to_payroll_at), "created_at": iso(c.created_at)}


# ---------------------------------------------------------------
# entry validation + apply (shared by Admin/HR and Employee side)
# ---------------------------------------------------------------
def validate_day_total(company, employee, day, hours, setting, exclude_pk=None):
    qs = TimesheetEntry.objects.filter(company=company, employee=employee, work_date=day, is_active=True).exclude(status="Rejected")
    if exclude_pk:
        qs = qs.exclude(pk=exclude_pk)
    total = (qs.aggregate(s=Sum("hours"))["s"] or Decimal("0")) + hours
    if total > setting.max_daily_hours:
        raise ValueError(f"Total hours for {day.isoformat()} would be {fmt_hours(total)}, above the daily limit of {fmt_hours(setting.max_daily_hours)}.")


def apply_entry(co, e, d, creating, setting, self_service=False):
    """Fill/validate a TimesheetEntry from request data. e.employee must already be set when creating."""
    if not creating and "project" in d:
        e.project = find_project(co, d["project"])
    if creating:
        e.project = find_project(co, d.get("project"))
    if e.project.status not in OPEN_PROJECT and (creating or "project" in d):
        raise ValueError(f"Project {e.project.code} is {e.project.status.lower()}; hours cannot be logged on it.")
    if self_service and (creating or "project" in d) and setting.enforce_allocation and e.project.allocations.filter(is_active=True).exists():
        t = timezone.localdate()
        if not e.project.allocations.filter(is_active=True, employee=e.employee, start_date__lte=t).filter(Q(end_date__isnull=True) | Q(end_date__gte=t)).exists():
            raise ValueError(f"You are not allocated to project {e.project.code}.")
    if creating or "work_date" in d:
        wd = to_date(d.get("work_date")) if "work_date" in d else None
        if wd is None:
            if creating:
                raise ValueError("work_date is required (YYYY-MM-DD).")
        else:
            t = timezone.localdate()
            if self_service:
                if wd > t:
                    raise ValueError("You cannot log hours for a future date.")
                if setting.backdate_limit_days and (t - wd).days > setting.backdate_limit_days:
                    raise ValueError(f"Hours can be logged only up to {setting.backdate_limit_days} days back.")
            e.work_date = wd
            e.week_start = week_bounds(wd, setting.week_start_day)[0]
    if creating or "task_summary" in d:
        ts = (d.get("task_summary") or "").strip()
        if not ts:
            raise ValueError("task_summary is required.")
        e.task_summary = ts[:500]
    if creating or "hours" in d:
        h = to_decimal(d.get("hours"))
        if h is None:
            raise ValueError("hours is required.")
        if h <= 0:
            raise ValueError("hours must be greater than 0.")
        if h > setting.max_daily_hours:
            raise ValueError(f"hours cannot exceed {fmt_hours(setting.max_daily_hours)} in a day.")
        e.hours = h.quantize(Q2)
    validate_day_total(co, e.employee, e.work_date, e.hours, setting, exclude_pk=e.pk)
    if "overtime_hours" in d and d["overtime_hours"] not in (None, ""):
        ot = to_decimal(d["overtime_hours"])
        if ot < 0 or ot > e.hours:
            raise ValueError("overtime_hours must be between 0 and hours.")
        e.overtime_hours, e.ot_manual = ot.quantize(Q2), True
    elif "overtime_hours" in d:                        # explicit null -> back to automatic
        e.ot_manual = False
    if "is_billable" in d:
        e.is_billable = to_bool(d["is_billable"], True)
    elif creating:
        e.is_billable = e.project.is_billable
