# ============================================================
# ADDITIVE: Organization & Workforce Intelligence API
#
#   GET  /api/people/org/dashboard/            org structure, holidays, new joining, birthdays (with department)
#   GET  /api/people/org/departments/          all departments with head + headcount
#   GET  /api/people/org/departments/<id>/     department details: head, branch split, members + 360 links
#   POST /api/people/org/departments/<id>/head/   {head, deputy?}  department responsibility
#   GET  /api/people/org/departments/unassigned/  departments that have no head yet
# ============================================================
from collections import Counter
from datetime import timedelta

from django.db import transaction
from django.db.models import Count, Q
from django.utils import timezone
from rest_framework.views import APIView

from Company.models import Holiday
from Employee.models import Department, EmployeeDT

from .common import PeopleAuthMixin, dept_name, employees_qs, err, iso, ok
from .models import Branch, EmployeeExtra
from .org_models import DepartmentOwnership      # direct import: works even if models.py lacks the star-import

UNASSIGNED = "Unassigned"


def dept_label(emp):
    """Department for display. Uses the FK, then the legacy text column, never an empty dash."""
    return dept_name(emp) or emp.Sub_Department or UNASSIGNED


def member_row(e):
    return {"id": e.id, "employee_code": e.employee_code, "name": e.name, "designation": e.Designation,
            "department": dept_label(e),
            "profile360_api": f"/api/people/profile360/{e.employee_code}/",
            "profile360_path": f"/employees/{e.employee_code}/360"}


def owner_of(dep):
    try:
        return dep.ownership
    except DepartmentOwnership.DoesNotExist:
        return None


def dept_summary(dep, members_qs):
    o = owner_of(dep)
    head = o.head if o and o.head_id else None
    return {"id": dep.id, "name": dep.name, "code": dep.code, "headcount": members_qs.count(),
            "head": member_row(head) if head else None,
            "deputy": member_row(o.deputy) if o and o.deputy_id else None,
            "head_assigned": head is not None}


def members_of(company, dep):
    return employees_qs(company).filter(is_active=True).filter(
        Q(department=dep) | Q(department__isnull=True, Department__iexact=dep.name))


class OrgDashboardView(PeopleAuthMixin, APIView):
    permission_action = "view"

    def get(self, request):
        company, today = self.company(), timezone.localdate()
        emps = list(employees_qs(company).filter(is_active=True).select_related("department"))
        deps = list(Department.objects.filter(company=company, is_active=True))
        counts = Counter()
        for e in emps:
            counts[dept_label(e)] += 1
        owners = {o.department_id: o for o in DepartmentOwnership.objects.filter(
            company=company, is_active=True).select_related("head")}
        leaders = {o.head_id for o in owners.values() if o.head_id}
        leaders |= set(EmployeeExtra.objects.filter(company=company, reporting_manager__isnull=False)
                       .values_list("reporting_manager_id", flat=True))
        branches = Counter(b for b in EmployeeExtra.objects.filter(
            company=company, employee__in=[e.id for e in emps]).values_list("branch__name", flat=True) if b)
        dept_rows = []
        for d in deps:
            o = owners.get(d.id)
            dept_rows.append({"id": d.id, "name": d.name, "headcount": counts.get(d.name, 0),
                              "head": ({"employee_code": o.head.employee_code, "name": o.head.name}
                                       if o and o.head_id else None),
                              "head_assigned": bool(o and o.head_id)})
        company_name = getattr(company, "Registered_Company_Name", None) or str(company)

        # birthdays: next 30 days, with a real department
        def next_birthday(dob):
            try:
                nb = dob.replace(year=today.year)
            except ValueError:              # 29 Feb
                nb = dob.replace(year=today.year, day=28)
            return nb if nb >= today else nb.replace(year=today.year + 1)
        births = []
        for e in emps:
            if e.Date_of_Birth:
                nb = next_birthday(e.Date_of_Birth)
                if (nb - today).days <= 30:
                    births.append((nb, e))
        births.sort(key=lambda t: t[0])
        joined = [e for e in emps if e.Date_of_Joining and e.Date_of_Joining >= today - timedelta(days=30)]
        joined.sort(key=lambda e: e.Date_of_Joining, reverse=True)
        hols = Holiday.objects.filter(company=company, is_active=True, date__gte=today).order_by("date")[:5]
        return ok("ORG_DASHBOARD", "Organization & workforce intelligence.", {
            "company": company_name,
            "summary": {"total_employees": len(emps), "leaders": len(leaders), "departments": len(deps),
                        "teams": len({e.team_Department for e in emps if e.team_Department}),
                        "locations": len(branches)},
            "departments": sorted(dept_rows, key=lambda r: -r["headcount"]),
            "departments_without_head": [r["name"] for r in dept_rows if not r["head_assigned"]],
            "locations": [{"name": n, "count": c} for n, c in branches.most_common()],
            "holidays": [{"date": h.date, "name": h.name, "day": h.date.strftime("%A")} for h in hols],
            "new_joining": [{**member_row(e), "joining_date": iso(e.Date_of_Joining)} for e in joined[:10]],
            "birthdays": [{**member_row(e), "birthday": nb.strftime("%d %b"), "date": iso(nb),
                           "days_left": (nb - today).days} for nb, e in births[:10]],
        })


class DepartmentListView(PeopleAuthMixin, APIView):
    permission_action = "view"

    def get(self, request):
        company = self.company()
        rows = [dept_summary(d, members_of(company, d)) for d in
                Department.objects.filter(company=company, is_active=True)]
        return ok("ORG_DEPARTMENTS", "Departments.", rows,
                  without_head=sum(1 for r in rows if not r["head_assigned"]))


class DepartmentUnassignedView(PeopleAuthMixin, APIView):
    permission_action = "view"

    def get(self, request):
        company = self.company()
        rows = [dept_summary(d, members_of(company, d)) for d in
                Department.objects.filter(company=company, is_active=True)]
        rows = [r for r in rows if not r["head_assigned"]]
        return ok("ORG_DEPARTMENTS_UNASSIGNED", "Departments with no head.", rows, total=len(rows))


class DepartmentDetailView(PeopleAuthMixin, APIView):
    permission_action = "view"

    def get(self, request, pk):
        company = self.company()
        dep = Department.objects.filter(company=company, is_active=True, pk=pk).first()
        if dep is None:
            return err("NOT_FOUND", "Department not found.", 404)
        members = members_of(company, dep).select_related("department")
        by_branch = Counter(
            (EmployeeExtra.objects.filter(employee=m).values_list("branch__name", flat=True).first() or "No branch")
            for m in members)
        data = dept_summary(dep, members)
        data.update({
            "branch_distribution": [{"branch": b, "count": c} for b, c in by_branch.most_common()],
            "members": [member_row(m) for m in members.order_by("name")],
            "responsibility_note": None if data["head_assigned"] else
            "No department head assigned. Departmental responsibility must rest with someone - assign a head.",
        })
        return ok("ORG_DEPARTMENT_DETAIL", "Department details.", data)


class DepartmentHeadView(PeopleAuthMixin, APIView):
    permission_action = "edit"

    @transaction.atomic
    def post(self, request, pk):
        company, d = self.company(), request.data
        dep = Department.objects.filter(company=company, is_active=True, pk=pk).first()
        if dep is None:
            return err("NOT_FOUND", "Department not found.", 404)
        code = (d.get("head") or "").strip()
        if not code:
            return err("VALIDATION", "head (employee_code) is required - a department cannot be left without an owner.")
        head = employees_qs(company).filter(employee_code=code, is_active=True).first()
        if head is None:
            return err("VALIDATION", f"'{code}' is not an active employee of your company.")
        deputy = None
        if d.get("deputy"):
            deputy = employees_qs(company).filter(employee_code=str(d["deputy"]).strip(), is_active=True).first()
            if deputy is None:
                return err("VALIDATION", "deputy is not an active employee of your company.")
            if deputy.pk == head.pk:
                return err("VALIDATION", "Head and deputy must be different people.")
        o, _ = DepartmentOwnership.objects.get_or_create(
            department=dep, defaults={"company": company, "created_by": self.actor()})
        o.head, o.deputy, o.updated_by, o.is_active = head, deputy, self.actor(), True
        o.save()
        return ok("ORG_DEPARTMENT_HEAD_SET", "Department head assigned.", dept_summary(dep, members_of(company, dep)))
