# ============================================================
# HR Cases / Grievances / Complaints  -  ONE registry (ERCase), three filtered views
#   /api/relations/cases/   /grievances/   /complaints/
# ============================================================
from datetime import timedelta

from django.db import IntegrityError
from django.utils import timezone
from rest_framework.decorators import action

from .common import (CATEGORIES, OPEN_CASE, RESOLUTION_TYPES, SEVERITIES, TRANSITIONS, RelCrud, add_note, case_row, central_audit, check_conflict, emp_by_code,
                     err, get_setting, new_token, next_no, norm, note_row, ok, to_bool, to_date)
from .models import ERCase


class NumberedCreate:
    """create() with retry when two requests race for the same number (unique company + number)."""
    def create(self, request):
        for i in range(4):
            try:
                r = super().create(request)
            except IntegrityError:
                continue
            return r
        return err("CONFLICT", "Could not allocate a unique number, please retry.", 409)


class CaseViewSet(NumberedCreate, RelCrud):
    """
    CRUD   /api/relations/cases/                     ?status= ?severity= ?category= ?employee=<code> ?investigator=<code> ?source= ?overdue=true ?date_from= ?date_to= ?search=
    POST   /api/relations/cases/                     [Raise New Case]
           {employee_code, category, subject, description?, severity?, sub_category?, incident_date?, target_date?, is_confidential?, source?, raised_by_code?, investigator_code?}
    POST   /api/relations/cases/<id>/assign/   {investigator_code, remarks?}
    POST   /api/relations/cases/<id>/status/   {status, remarks?}               (guarded transitions)
    POST   /api/relations/cases/<id>/resolve/  {resolution_type, resolution_summary}   [Resolve Case]
    POST   /api/relations/cases/<id>/close/    {remarks?}      POST /<id>/reopen/ {remarks}      POST /<id>/escalate/ {remarks}
    GET/POST /api/relations/cases/<id>/notes/  {text, is_internal?}  investigation notes + timeline
    """
    model, code, module_label, ref_field = ERCase, "ER_CASE", "HR Cases", "case_id"
    select = ("employee", "investigator", "raised_by", "employee__department")
    search_fields = ("subject", "case_no", "employee__name", "employee__employee_code", "sub_category")
    fixed_category = None
    permission_action_map = {"assign": "edit", "status": "edit", "escalate": "edit", "resolve": "approve", "close": "approve", "reopen": "approve", "summary": "view"}

    def build(self, c):
        return case_row(c, self.request)

    def scope(self):
        qs = super().scope()
        return qs.filter(category=self.fixed_category) if self.fixed_category else qs

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("severity"):
            qs = qs.filter(severity__iexact=p["severity"])
        if p.get("category") and not self.fixed_category:
            qs = qs.filter(category__iexact=p["category"])
        if p.get("source"):
            qs = qs.filter(source__iexact=p["source"])
        if p.get("investigator"):
            qs = qs.filter(investigator__employee_code=p["investigator"])
        if p.get("date_from"):
            qs = qs.filter(opened_at__date__gte=to_date(p["date_from"]))
        if p.get("date_to"):
            qs = qs.filter(opened_at__date__lte=to_date(p["date_to"]))
        if str(p.get("overdue", "")).lower() in ("1", "true", "yes"):
            qs = qs.filter(target_date__lt=timezone.localdate(), status__in=OPEN_CASE)
        return qs

    def list(self, request):
        try:
            return super().list(request)
        except ValueError as e:
            return err("VALIDATION", str(e))

    def retrieve(self, request, pk=None):
        c = self.scope().filter(pk=pk, is_active=True).first()
        if c is None:
            return err("NOT_FOUND", "Record not found.", 404)
        d = case_row(c, request, counts=True)
        d["timeline"] = [note_row(n) for n in c.notes.filter(is_active=True)]
        return ok(f"{self.code}_DETAIL", "Detail fetched.", d)

    # ---------- validation ----------
    def _dup_check(self, c):
        q = ERCase.objects.filter(employee=c.employee, raised_by=c.raised_by, category=c.category, status__in=OPEN_CASE)
        if c.pk:
            q = q.exclude(pk=c.pk)
        for o in q.filter(company=self.company(), is_active=True):
            if norm(o.subject) == norm(c.subject):
                raise ValueError(f"Duplicate: an open {c.category.lower()} case with the same subject already exists for this employee ({o.case_no}).")

    def _set_investigator(self, c, code):
        if not code:
            c.investigator = None
            return
        inv = emp_by_code(self.company(), code)
        check_conflict(c, inv)
        c.investigator = inv
        if c.status == "Open":
            c.status = "In Investigation"

    def apply(self, c, d, creating):
        co, today = self.company(), timezone.localdate()
        if not creating and c.status in ("Resolved", "Closed", "Withdrawn"):
            raise ValueError(f"A {c.status.lower()} case cannot be edited. Reopen it first.")
        if creating:
            c.employee = emp_by_code(co, d.get("employee_code"))
            cat = self.fixed_category or d.get("category")
            cat = next((x for x in CATEGORIES if x.lower() == str(cat or "").lower()), None)
            if cat is None:
                raise ValueError(f"category must be one of: {', '.join(CATEGORIES)}.")
            c.category = cat
            if d.get("raised_by_code"):
                c.raised_by = emp_by_code(co, d["raised_by_code"])
            c.source = d.get("source") or "HR"
            if c.source not in dict(ERCase.SOURCES):
                raise ValueError(f"source must be one of: {', '.join(dict(ERCase.SOURCES))}.")
        elif "category" in d and not self.fixed_category:
            cat = next((x for x in CATEGORIES if x.lower() == str(d["category"]).lower()), None)
            if cat is None:
                raise ValueError(f"category must be one of: {', '.join(CATEGORIES)}.")
            c.category = cat
        subj = (d.get("subject") or c.subject or "").strip()
        if not subj:
            raise ValueError("subject is required.")
        c.subject = subj[:300]
        for k in ("description", "sub_category"):
            if k in d:
                setattr(c, k, d[k])
        if "severity" in d or creating:
            sv = next((x for x in SEVERITIES if x.lower() == str(d.get("severity") or "Medium").lower()), None)
            if sv is None:
                raise ValueError(f"severity must be one of: {', '.join(SEVERITIES)}.")
            c.severity = sv
        if "incident_date" in d:
            i = to_date(d["incident_date"])
            if i and i > today:
                raise ValueError("incident_date cannot be in the future.")
            c.incident_date = i
        if "target_date" in d:
            t = to_date(d["target_date"])
            if t and t < today and creating:
                raise ValueError("target_date cannot be in the past.")
            c.target_date = t
        if "is_confidential" in d:
            c.is_confidential = to_bool(d["is_confidential"], True)
        if creating and self.fixed_category == "Complaint" and not c.sub_category:
            c.sub_category = "Code of Conduct"
        if "investigator_code" in d:
            self._set_investigator(c, d["investigator_code"])
        elif creating and c.sub_category and c.sub_category.upper() == "POSH":      # POSH complaints go to the ICC presiding officer
            icc = get_setting(co).icc_presiding_officer
            if icc is not None:
                try:
                    check_conflict(c, icc)
                    c.investigator, c.status = icc, "In Investigation"
                except ValueError:
                    pass
        self._dup_check(c)
        if creating:
            c.case_no = next_no(ERCase, co, "case_no", "CASE-", 2)

    def after_save(self, c, creating):
        if creating:
            add_note(c, self.request.user, f"Case {c.case_no} raised ({c.category}, {c.severity}).", "Created", True)
            if c.investigator_id:
                add_note(c, self.request.user, f"Assigned to {c.investigator.name}.", "Assigned", True)

    def before_delete(self, c):
        if c.status in ("In Investigation", "Pending Review", "Escalated"):
            raise ValueError("A case under investigation cannot be deleted. Withdraw or resolve it first.")
        if c.documents.filter(is_active=True).exists() or c.warnings.filter(is_active=True).exists() or c.disciplinary_actions.filter(is_active=True).exists() \
                or c.legal_cases.filter(is_active=True).exists():
            raise ValueError("Linked documents / warnings / disciplinary or legal records exist; remove them first.")

    # ---------- workflow ----------
    def _case(self, pk):
        return self.scope().filter(pk=pk, is_active=True).select_related("employee", "investigator", "raised_by").first()

    def _move(self, c, to, request, remarks=None, note_type="Status"):
        if to not in TRANSITIONS.get(c.status, set()):
            return err("INVALID_STATE", f"A case cannot move from {c.status} to {to}.", 409)
        old = c.status
        c.status, c.updated_by = to, self.actor()
        if to in ("Resolved",):
            c.resolved_at, c.resolved_by = timezone.now(), self.actor()
        if to == "Closed":
            c.closed_at = timezone.now()
        if old in ("Resolved", "Closed") and to == "In Investigation":
            c.resolved_at = c.closed_at = None
            note_type = "Reopened"
        c.save()
        add_note(c, request.user, f"Status changed {old} -> {to}." + (f" {remarks}" if remarks else ""), note_type, True)
        central_audit(request, self.company(), "STATUS", self.module_label, c.case_no, {"status": old}, {"status": to})
        return ok("ER_CASE_STATUS", f"Case moved to {to}.", case_row(c, request))

    @action(detail=True, methods=["post"], url_path="assign")
    def assign(self, request, pk=None):
        c = self._case(pk)
        if c is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if c.status in ("Resolved", "Closed", "Withdrawn"):
            return err("INVALID_STATE", f"A {c.status.lower()} case cannot be reassigned.", 409)
        try:
            self._set_investigator(c, request.data.get("investigator_code"))
        except ValueError as e:
            return err("VALIDATION", str(e))
        if c.investigator_id is None:
            return err("VALIDATION", "investigator_code is required.")
        c.updated_by = self.actor()
        c.save()
        add_note(c, request.user, f"Assigned to {c.investigator.name}." + (f" {request.data['remarks']}" if request.data.get("remarks") else ""), "Assigned", True)
        central_audit(request, self.company(), "ASSIGNED", self.module_label, c.case_no, None, {"investigator": c.investigator.employee_code})
        return ok("ER_CASE_ASSIGNED", "Investigator assigned.", case_row(c, request))

    @action(detail=True, methods=["post"], url_path="status")
    def status(self, request, pk=None):
        c = self._case(pk)
        if c is None:
            return err("NOT_FOUND", "Record not found.", 404)
        to = request.data.get("status")
        if to not in ("Open", "In Investigation", "Pending Review", "Escalated", "Withdrawn"):
            return err("VALIDATION", "status must be one of: Open, In Investigation, Pending Review, Escalated, Withdrawn. Use resolve / close / reopen for the others.")
        if to == "In Investigation" and not c.investigator_id:
            return err("VALIDATION", "Assign an investigator before moving the case to In Investigation.")
        return self._move(c, to, request, request.data.get("remarks"))

    @action(detail=True, methods=["post"], url_path="escalate")
    def escalate(self, request, pk=None):
        c = self._case(pk)
        return self._move(c, "Escalated", request, request.data.get("remarks")) if c else err("NOT_FOUND", "Record not found.", 404)

    @action(detail=True, methods=["post"], url_path="resolve")
    def resolve(self, request, pk=None):
        c = self._case(pk)
        if c is None:
            return err("NOT_FOUND", "Record not found.", 404)
        rt, rs = request.data.get("resolution_type"), (request.data.get("resolution_summary") or "").strip()
        rt = next((x for x in RESOLUTION_TYPES if x.lower() == str(rt or "").lower()), None)
        if rt is None:
            return err("VALIDATION", f"resolution_type must be one of: {', '.join(RESOLUTION_TYPES)}.")
        if not rs:
            return err("VALIDATION", "resolution_summary is required.")
        if c.status not in TRANSITIONS or "Resolved" not in TRANSITIONS[c.status]:
            return err("INVALID_STATE", f"A {c.status.lower()} case cannot be resolved.", 409)
        c.resolution_type, c.resolution_summary = rt, rs
        return self._move(c, "Resolved", request, f"{rt}.", "Resolved")

    @action(detail=True, methods=["post"], url_path="close")
    def close(self, request, pk=None):
        c = self._case(pk)
        return self._move(c, "Closed", request, request.data.get("remarks")) if c else err("NOT_FOUND", "Record not found.", 404)

    @action(detail=True, methods=["post"], url_path="reopen")
    def reopen(self, request, pk=None):
        c = self._case(pk)
        if c is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if not (request.data.get("remarks") or "").strip():
            return err("VALIDATION", "remarks are required to reopen a case.")
        if not c.investigator_id:
            return err("VALIDATION", "Assign an investigator before reopening.")
        return self._move(c, "In Investigation", request, request.data["remarks"])

    @action(detail=True, methods=["get", "post"], url_path="notes")
    def notes(self, request, pk=None):
        c = self._case(pk)
        if c is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if request.method == "GET":
            return ok("ER_CASE_NOTES", "Timeline.", [note_row(n) for n in c.notes.filter(is_active=True)])
        text = (request.data.get("text") or "").strip()
        if not text:
            return err("VALIDATION", "text is required.")
        n = add_note(c, request.user, text, "Note", to_bool(request.data.get("is_internal"), True))
        return ok("ER_CASE_NOTE_ADDED", "Note added.", note_row(n), 201)

    @action(detail=False, methods=["get"], url_path="summary")
    def summary(self, request):
        qs = self.scope().filter(is_active=True)
        cnt = lambda **k: qs.filter(**k).count()
        return ok("ER_CASE_SUMMARY", "Summary.", {"total": qs.count(), "open": qs.filter(status__in=OPEN_CASE).count(), "resolved": cnt(status="Resolved"), "closed": cnt(status="Closed"),
                                                  "by_severity": {s: qs.filter(status__in=OPEN_CASE, severity=s).count() for s in SEVERITIES}})


class GrievanceViewSet(CaseViewSet):
    """Grievances tab = the same registry, category fixed to Grievance.   /api/relations/grievances/  (same fields, actions and filters as /cases/)"""
    code, module_label, fixed_category = "GRIEVANCE", "Grievances", "Grievance"


class ComplaintViewSet(CaseViewSet):
    """
    Complaints tab (POSH & code of conduct) = same registry, category fixed to Complaint.   /api/relations/complaints/
    sub_category: "POSH" | "Code of Conduct" | other.  POSH complaints are auto-assigned to the ICC presiding officer (Settings) when one is set.
    GET /api/relations/complaints/committee/   the banner of the tab (active complaints this quarter + ICC info)
    """
    code, module_label, fixed_category = "COMPLAINT", "Complaints", "Complaint"
    permission_action_map = {**CaseViewSet.permission_action_map, "committee": "view"}

    @action(detail=False, methods=["get"], url_path="committee")
    def committee(self, request):
        co, t = self.company(), timezone.localdate()
        q0 = t.replace(month=((t.month - 1) // 3) * 3 + 1, day=1)
        s = get_setting(co)
        n = ERCase.objects.filter(company=co, is_active=True, category="Complaint", status__in=OPEN_CASE, opened_at__date__gte=q0).count()
        freq = s.icc_meeting_frequency.lower()
        msg = (f"Zero active formal sexual harassment or code of conduct complaints on record for the current quarter. Internal Complaints Committee (ICC) meets {freq}."
               if n == 0 else f"{n} active formal complaint(s) on record for the current quarter. Internal Complaints Committee (ICC) meets {freq}.")
        from .common import emp_brief
        return ok("COMPLAINT_COMMITTEE", msg, {"active_this_quarter": n, "quarter_start": q0.isoformat(), "icc_meeting_frequency": s.icc_meeting_frequency,
                                               "icc_presiding_officer": emp_brief(s.icc_presiding_officer, request) if s.icc_presiding_officer_id else None, "message": msg})
