# ============================================================
# ADDITIVE: HR MIS & Workforce Analytics - Employee self-service API
# ------------------------------------------------------------
# Mounted at /employee/reports/   (see People/reports_self_urls.py)
# Auth: Employee JWT.
#   - own reports  : an employee only ever sees THEIR OWN numbers
#   - team reports : a manager (Reporting Hierarchy) sees only direct reports;
#                    payroll is never part of the team reports.
# The same analytics engine as the Admin API is used with the data scoped to the
# employee(s) - nothing is duplicated.
#
#   GET summary/          my attendance / leave / training / rating / latest payslip at a glance
#   GET attendance/       my muster + punctuality           (?month=2026-09 | ?financial_year= | ?from=&to=)
#   GET leave/            my leave utilisation + encashable balance
#   GET payroll/          my payroll trend (own payslips only)
#   GET training/         my hours, certificates, courses
#   GET performance/      my rating history / bell-curve position
#   GET team/summary/     (managers) team headcount, attendance, leave, rating
#   GET team/attendance/  GET team/leave/   GET team/training/   GET team/performance/
# ============================================================

from . import reports_engine as en
from .common import err, ok, to_bool, to_int
from .views_employee_vault import EmployeeBase
from rest_framework.views import APIView


class Base(EmployeeBase, APIView):
    def codes(self):
        return [self.me.employee_code]

    def period(self):
        return en.period_from(self.request.query_params)


class SelfReport(Base):
    kind = None

    def get(self, request):
        co, codes = self.company(), self.codes()
        try:
            if self.kind == "performance":
                data = en.performance(co, request.query_params, codes)
            else:
                start, end, fy = self.period()
                if self.kind == "attendance":
                    data = en.attendance(co, start, end, fy, codes, muster=True, limit=100)
                elif self.kind == "leave":
                    data = en.leave(co, start, end, fy, codes)
                elif self.kind == "payroll":
                    data = en.payroll(co, start, end, fy, codes)
                else:
                    data = en.training(co, start, end, fy, codes)
        except ValueError as e:
            return err("VALIDATION", str(e))
        return ok(f"MY_REPORT_{self.kind.upper()}", "Report fetched.", data)


class MyAttendanceReport(SelfReport):
    kind = "attendance"


class MyLeaveReport(SelfReport):
    kind = "leave"


class MyPayrollReport(SelfReport):
    kind = "payroll"


class MyTrainingReport(SelfReport):
    kind = "training"


class MyPerformanceReport(SelfReport):
    kind = "performance"


def summary_for(company, codes, params):
    """Compact multi-report overview used by both my/ and team/ summary."""
    start, end, fy = en.period_from(params)
    att = en.attendance(company, start, end, fy, codes)
    lv = en.leave(company, start, end, fy, codes)
    tr = en.training(company, start, end, fy, codes, catalog_limit=0)
    pf = en.performance(company, params, codes)
    return {
        "period": {"from": str(start), "to": str(end), "financial_year": fy},
        "attendance": {"insight": att["insight"], "summary": att["summary"], "punctuality": att["punctuality"]},
        "leave": {"utilization": lv["utilization"], "encashable_liability": lv["liability"]["total_amount_label"]},
        "training": {k: {"label": v["label"], "value": v["value"]} for k, v in tr["cards"].items()},
        "performance": {"average_rating": pf.get("average_rating"), "total_rated": pf.get("total_rated"),
                        "distribution": [{"rating": r["rating"], "count": r["count"], "percent": r["percent"]} for r in pf["distribution"]]},
    }


class MyReportSummary(Base):
    def get(self, request):
        co = self.company()
        try:
            data = summary_for(co, self.codes(), request.query_params)
        except ValueError as e:
            return err("VALIDATION", str(e))
        start, end, fy = en.period_from(request.query_params)
        pm = en.payroll(co, start, end, fy, self.codes())
        data["payroll"] = {"months_processed": pm["budget"]["months_processed"], "ytd_gross_label": pm["budget"]["ytd_gross_label"],
                           "latest_month": pm["monthly_trend"][-1] if pm["monthly_trend"] else None}
        data["employee"] = {"employee_code": self.me.employee_code, "name": self.me.name}
        return ok("MY_REPORT_SUMMARY", "My report summary.", data)


# ---------------- manager / team ----------------

class TeamBase(Base):
    def codes(self):
        return en.direct_reports(self.company(), self.me.employee_code)

    def guard(self):
        if not self.codes():
            return err("NOT_A_MANAGER", "You have no direct reports.", 403)
        return None


class TeamReport(TeamBase):
    kind = None

    def get(self, request):
        blocked = self.guard()
        if blocked:
            return blocked
        co, codes = self.company(), self.codes()
        try:
            if self.kind == "summary":
                data = summary_for(co, codes, request.query_params)
                data["team_size"] = len(codes)
            elif self.kind == "performance":
                data = en.performance(co, request.query_params, codes)
            else:
                start, end, fy = self.period()
                if self.kind == "attendance":
                    data = en.attendance(co, start, end, fy, codes, muster=True, limit=100)
                elif self.kind == "leave":
                    data = en.leave(co, start, end, fy, codes)
                else:
                    data = en.training(co, start, end, fy, codes)
        except ValueError as e:
            return err("VALIDATION", str(e))
        return ok(f"TEAM_REPORT_{self.kind.upper()}", "Team report fetched.", data)


class TeamSummary(TeamReport):
    kind = "summary"


class TeamAttendance(TeamReport):
    kind = "attendance"


class TeamLeave(TeamReport):
    kind = "leave"


class TeamTraining(TeamReport):
    kind = "training"


class TeamPerformance(TeamReport):
    kind = "performance"
