# ============================================================
# EMPLOYEE SIDE (self-service)       /employee/relations/
# Auth: Employee JWT.  An employee sees only what concerns THEM:
#   cases they raised (public notes only) - warnings and disciplinary notices addressed to them - cases assigned to them as investigator.
# Confidential vault documents and HR-internal notes are never exposed here.
# ============================================================
from datetime import timedelta

from django.utils import timezone
from rest_framework.views import APIView

from Employee.employee_authentication import EmployeeJWTAuthentication, IsEmployeeAuthenticated
from Employee.employee_crud_permissions import actor_label

from .common import (OPEN_CASE, TRANSITIONS, DisciplinaryAction, ERCase, WarningLetter, add_note, case_row, check_conflict, central_audit, disc_row, emp_brief,
                     emp_by_code, err, get_setting, iso, letter_row, new_token, next_no, norm, note_row, ok, paginate, to_date, who)
from .models import CaseNote
from .views_cases import NumberedCreate  # noqa: F401
from .views_discipline import preview_letter, warning_row

EMP_CATEGORIES = ["Grievance", "Complaint", "Harassment", "Misconduct", "Policy Violation", "Other"]
RESOLVE_TYPES = ["Substantiated", "Partially Substantiated", "Unsubstantiated", "Settled", "No Action Required"]
APPEAL_DAYS = 15


class SelfBase(APIView):
    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    @property
    def me(self):
        return self.request.user

    @property
    def company(self):
        return self.request.user.company

    def actor(self):
        return actor_label(self.me)


def my_case_view(c, request):
    """What the person who raised a case may see (no investigator, no severity, no internal notes)."""
    d = {"id": c.id, "case_id": c.case_no, "category": c.category, "sub_category": c.sub_category, "subject": c.subject, "description": c.description,
         "status": c.status, "incident_date": iso(c.incident_date), "opened_at": iso(c.opened_at), "target_date": iso(c.target_date),
         "is_anonymous": c.source == "Anonymous", "about_employee": emp_brief(c.employee, request)["name"] if c.employee_id else None,
         "can_edit": c.status == "Open" and not c.investigator_id, "can_withdraw": c.status in ("Open", "In Investigation", "Pending Review")}
    if c.status in ("Resolved", "Closed"):
        d.update(resolution_type=c.resolution_type, resolution_summary=c.resolution_summary, resolved_at=iso(c.resolved_at))
    return d


class MyDashboard(SelfBase):
    """GET /employee/relations/dashboard/"""

    def get(self, request):
        co, me = self.company, self.me
        mine = ERCase.objects.filter(company=co, is_active=True, raised_by=me)
        return ok("MY_RELATIONS_DASHBOARD", "My employee-relations dashboard.", {
            "my_cases_open": mine.filter(status__in=OPEN_CASE).count(), "my_cases_resolved": mine.filter(status__in=["Resolved", "Closed"]).count(),
            "warnings_to_acknowledge": WarningLetter.objects.filter(company=co, is_active=True, employee=me, status="Issued").count(),
            "disciplinary_notices_open": DisciplinaryAction.objects.filter(company=co, is_active=True, employee=me).exclude(status__in=["Closed", "Cancelled", "Decision Issued", "Appealed"]).count(),
            "investigations_assigned": ERCase.objects.filter(company=co, is_active=True, investigator=me, status__in=OPEN_CASE).count()})


# ---------------- cases I raised ----------------
class MyCases(SelfBase):
    """
    GET  /employee/relations/cases/          ?status= ?category=
    POST /employee/relations/cases/          [Raise New Case]  {category: Grievance|Complaint|Harassment|Misconduct|Policy Violation|Other, subject, description?, sub_category?,
                                              incident_date?, against_employee_code?, anonymous?: true}
         anonymous=true stores NO link to you; the response contains a one-time `tracking_token` to follow the case with POST /employee/relations/track/
    """

    def get(self, request):
        qs = ERCase.objects.filter(company=self.company, is_active=True, raised_by=self.me).order_by("-id")
        p = request.query_params
        if p.get("status"):
            qs = qs.filter(status=p["status"])
        if p.get("category"):
            qs = qs.filter(category__iexact=p["category"])
        rows, meta = paginate(request, qs, lambda c: my_case_view(c, request))
        return ok("MY_CASES", "Cases raised by me.", rows, meta=meta)

    def post(self, request):
        co, me, d = self.company, self.me, request.data
        today = timezone.localdate()
        try:
            cat = next((x for x in EMP_CATEGORIES if x.lower() == str(d.get("category") or "").lower()), None)
            if cat is None:
                raise ValueError(f"category must be one of: {', '.join(EMP_CATEGORIES)}.")
            subj = (d.get("subject") or "").strip()
            if not subj:
                raise ValueError("subject is required.")
            anon = str(d.get("anonymous", "")).lower() in ("1", "true", "yes")
            about = emp_by_code(co, d["against_employee_code"]) if d.get("against_employee_code") else None
            if about is not None and about.pk == me.pk:
                raise ValueError("against_employee_code cannot be yourself.")
            inc = to_date(d.get("incident_date"))
            if inc and inc > today:
                raise ValueError("incident_date cannot be in the future.")
            since = timezone.now() - timedelta(hours=24)
            if not anon and ERCase.objects.filter(company=co, raised_by=me, opened_at__gte=since).count() >= 10:
                raise ValueError("You can raise at most 10 cases in 24 hours.")
            for o in ERCase.objects.filter(company=co, is_active=True, category=cat, status__in=OPEN_CASE, employee=about, **({} if anon else {"raised_by": me})):
                if norm(o.subject) == norm(subj) and (anon is False or o.source == "Anonymous"):
                    raise ValueError("Duplicate: you already have an open case with the same subject" + ("" if anon else f" ({o.case_no})") + ".")
            c = ERCase(company=co, category=cat, sub_category=d.get("sub_category"), subject=subj[:300], description=d.get("description"), employee=about,
                       severity="High" if cat == "Harassment" else "Medium", source="Anonymous" if anon else "Employee", is_confidential=True,
                       raised_by=None if anon else me, incident_date=inc, created_by=None if anon else self.actor(), updated_by=None if anon else self.actor())
            token = None
            if anon:
                token, c.tracking_hash = new_token()
            if cat == "Complaint" and not c.sub_category:
                c.sub_category = "Code of Conduct"
            if (c.sub_category or "").upper() == "POSH":
                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
            c.case_no = next_no(ERCase, co, "case_no", "CASE-", 2)
            c.save()
        except ValueError as e:
            return err("VALIDATION", str(e))
        add_note(c, None, f"Case {c.case_no} raised by employee ({'anonymous' if anon else 'identified'}).", "Created", True)
        if c.investigator_id:
            add_note(c, None, f"Assigned to {c.investigator.name}.", "Assigned", True)
        add_note(c, None, "Your case has been received. HR will update you here.", "Update", False)
        data = my_case_view(c, request)
        if token:
            data["tracking_token"] = token
            data["tracking_note"] = "Save this token now - it is shown only once and cannot be recovered."
        return ok("MY_CASE_CREATED", "Case raised. Your reference is " + c.case_no + ".", data, 201)


class MyCaseDetail(SelfBase):
    """
    GET / PATCH / PUT / DELETE  /employee/relations/cases/<id>/        edit while Open and unassigned; DELETE = withdraw
    POST /employee/relations/cases/<id>/update/   POST /employee/relations/cases/<id>/delete/   (POST-only clients)
    """

    def _c(self, pk):
        return ERCase.objects.filter(company=self.company, is_active=True, raised_by=self.me, pk=pk).first()

    def get(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        d = my_case_view(c, request)
        d["updates"] = [note_row(n) for n in c.notes.filter(is_active=True, is_internal=False)]
        return ok("MY_CASE", "Case.", d)

    def patch(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        if c.status != "Open" or c.investigator_id:
            return err("INVALID_STATE", "A case can be edited only while it is Open and not yet assigned. Add a note instead.", 409)
        d = request.data
        try:
            if "subject" in d:
                if not (d["subject"] or "").strip():
                    raise ValueError("subject cannot be empty.")
                c.subject = d["subject"].strip()[:300]
            for k in ("description", "sub_category"):
                if k in d:
                    setattr(c, k, d[k])
            if "incident_date" in d:
                i = to_date(d["incident_date"])
                if i and i > timezone.localdate():
                    raise ValueError("incident_date cannot be in the future.")
                c.incident_date = i
        except ValueError as e:
            return err("VALIDATION", str(e))
        c.updated_by = self.actor()
        c.save()
        add_note(c, self.me, "Case details updated by the employee.", "Update", True)
        return ok("MY_CASE_UPDATED", "Case updated.", my_case_view(c, request))

    put = patch

    def delete(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        if "Withdrawn" not in TRANSITIONS.get(c.status, set()):
            return err("INVALID_STATE", f"A {c.status.lower()} case cannot be withdrawn.", 409)
        c.status, c.updated_by = "Withdrawn", self.actor()
        c.save()
        add_note(c, self.me, "Case withdrawn by the employee.", "Status", True)
        return ok("MY_CASE_WITHDRAWN", "Case withdrawn.", my_case_view(c, request))


class MyCaseUpdatePost(MyCaseDetail):
    def post(self, request, pk):
        return self.patch(request, pk)


class MyCaseDeletePost(MyCaseDetail):
    def post(self, request, pk):
        return self.delete(request, pk)


class MyCaseNotes(SelfBase):
    """GET /employee/relations/cases/<id>/notes/   updates shared with me      POST {text}  add information to my case"""

    def _c(self, pk):
        return ERCase.objects.filter(company=self.company, is_active=True, raised_by=self.me, pk=pk).first()

    def get(self, request, pk):
        c = self._c(pk)
        return ok("MY_CASE_NOTES", "Updates.", [note_row(n) for n in c.notes.filter(is_active=True, is_internal=False)]) if c else err("NOT_FOUND", "Case not found.", 404)

    def post(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        if c.status in ("Closed", "Withdrawn"):
            return err("INVALID_STATE", f"A {c.status.lower()} case cannot receive new information.", 409)
        t = (request.data.get("text") or "").strip()
        if not t:
            return err("VALIDATION", "text is required.")
        return ok("MY_CASE_NOTE_ADDED", "Added.", note_row(add_note(c, self.me, t, "Note", False)), 201)


class TrackAnonymous(SelfBase):
    """POST /employee/relations/track/   {token}   status of an anonymous case (public updates only)"""

    def post(self, request):
        import hashlib
        t = (request.data.get("token") or "").strip()
        if not t:
            return err("VALIDATION", "token is required.")
        c = ERCase.objects.filter(company=self.company, is_active=True, tracking_hash=hashlib.sha256(t.encode()).hexdigest()).first()
        if c is None:
            return err("NOT_FOUND", "No case matches this token.", 404)
        d = my_case_view(c, request)
        d["updates"] = [note_row(n) for n in c.notes.filter(is_active=True, is_internal=False)]
        return ok("TRACKED_CASE", "Case status.", d)


# ---------------- warnings addressed to me ----------------
class MyWarnings(SelfBase):
    """GET /employee/relations/warnings/     ?status="""

    def get(self, request):
        qs = WarningLetter.objects.filter(company=self.company, is_active=True, employee=self.me).exclude(status="Draft").select_related("employee", "case", "letter").order_by("-id")
        if request.query_params.get("status"):
            qs = qs.filter(status=request.query_params["status"])
        rows, meta = paginate(request, qs, lambda w: {k: warning_row(w, request)[k] for k in ("id", "warning_id", "warning_level", "reason", "incident_date", "issued_on",
                                                                                             "valid_until", "status", "acknowledged_at")})
        return ok("MY_WARNINGS", "Warnings issued to me.", rows, meta=meta)


class MyWarningDetail(SelfBase):
    """GET /employee/relations/warnings/<id>/     [View Letter]"""

    def get(self, request, pk):
        w = WarningLetter.objects.filter(company=self.company, is_active=True, employee=self.me, pk=pk).exclude(status="Draft").select_related("employee", "letter").first()
        if w is None:
            return err("NOT_FOUND", "Warning not found.", 404)
        r = warning_row(w, request, True)
        r.pop("case", None)
        return ok("MY_WARNING", "Warning.", r)


class MyWarningAck(SelfBase):
    """POST /employee/relations/warnings/<id>/acknowledge/   {remarks?}   (acknowledges RECEIPT, not agreement)"""

    def post(self, request, pk):
        w = WarningLetter.objects.filter(company=self.company, is_active=True, employee=self.me, pk=pk).first()
        if w is None or w.status == "Draft":
            return err("NOT_FOUND", "Warning not found.", 404)
        if w.status != "Issued":
            return err("INVALID_STATE", f"This warning is {w.status}; only an issued warning can be acknowledged.", 409)
        w.status, w.acknowledged_at, w.acknowledgement_remarks, w.updated_by = "Acknowledged", timezone.now(), request.data.get("remarks"), self.actor()
        w.save()
        return ok("MY_WARNING_ACKNOWLEDGED", "Receipt acknowledged.", warning_row(w, request))


# ---------------- disciplinary notices addressed to me ----------------
class MyDisciplinary(SelfBase):
    """GET /employee/relations/disciplinary/"""

    def get(self, request):
        qs = DisciplinaryAction.objects.filter(company=self.company, is_active=True, employee=self.me).exclude(status="Cancelled").select_related("employee", "case").order_by("-id")
        rows, meta = paginate(request, qs, lambda d: _disc_mine(d, request))
        return ok("MY_DISCIPLINARY", "Disciplinary notices addressed to me.", rows, meta=meta)


def _disc_mine(d, request):
    r = disc_row(d, request)
    r.pop("case", None)
    r.pop("employee", None)
    r.pop("minutes", None)
    r["committee"] = [m["name"] for m in r["committee"]]
    return r


class MyDisciplinaryDetail(SelfBase):
    """GET /employee/relations/disciplinary/<id>/"""

    def get(self, request, pk):
        d = DisciplinaryAction.objects.filter(company=self.company, is_active=True, employee=self.me, pk=pk).exclude(status="Cancelled").first()
        return ok("MY_DISCIPLINARY_DETAIL", "Notice.", _disc_mine(d, request)) if d else err("NOT_FOUND", "Notice not found.", 404)


class MyDisciplinaryRespond(SelfBase):
    """POST /employee/relations/disciplinary/<id>/respond/  {response}   your written reply to the charge (editable until the decision)"""

    def post(self, request, pk):
        d = DisciplinaryAction.objects.filter(company=self.company, is_active=True, employee=self.me, pk=pk).first()
        if d is None:
            return err("NOT_FOUND", "Notice not found.", 404)
        if d.status not in ("Notice Issued", "Hearing Scheduled", "Hearing Held"):
            return err("INVALID_STATE", f"A reply can no longer be submitted (status: {d.status}).", 409)
        t = (request.data.get("response") or "").strip()
        if not t:
            return err("VALIDATION", "response is required.")
        d.employee_response, d.response_at, d.updated_by = t, timezone.now(), self.actor()
        d.save()
        return ok("MY_DISCIPLINARY_RESPONDED", "Your reply was recorded.", _disc_mine(d, request))


class MyDisciplinaryAppeal(SelfBase):
    """POST /employee/relations/disciplinary/<id>/appeal/  {reason}   within 15 days of the decision"""

    def post(self, request, pk):
        d = DisciplinaryAction.objects.filter(company=self.company, is_active=True, employee=self.me, pk=pk).first()
        if d is None:
            return err("NOT_FOUND", "Notice not found.", 404)
        if d.status != "Decision Issued":
            return err("INVALID_STATE", "Only an issued decision can be appealed.", 409)
        if d.decision_date and (timezone.localdate() - d.decision_date).days > APPEAL_DAYS:
            return err("INVALID_STATE", f"The {APPEAL_DAYS}-day appeal window has passed.", 409)
        t = (request.data.get("reason") or "").strip()
        if not t:
            return err("VALIDATION", "reason is required.")
        d.status, d.minutes, d.updated_by = "Appealed", ((d.minutes or "") + f"\n[Appeal by employee] {t}").strip(), self.actor()
        d.save()
        return ok("MY_DISCIPLINARY_APPEALED", "Appeal recorded.", _disc_mine(d, request))


# ---------------- cases assigned to me as investigator ----------------
class Investigations(SelfBase):
    """GET /employee/relations/investigations/    ?status=      cases assigned to me"""

    def get(self, request):
        qs = ERCase.objects.filter(company=self.company, is_active=True, investigator=self.me).select_related("employee", "investigator", "raised_by").order_by("-id")
        if request.query_params.get("status"):
            qs = qs.filter(status=request.query_params["status"])
        rows, meta = paginate(request, qs, lambda c: case_row(c, request, full=False))
        return ok("MY_INVESTIGATIONS", "Cases assigned to me.", rows, meta=meta)


class _Inv(SelfBase):
    def _c(self, pk):
        return ERCase.objects.filter(company=self.company, is_active=True, investigator=self.me, pk=pk).select_related("employee", "investigator", "raised_by").first()


class InvestigationDetail(_Inv):
    """GET /employee/relations/investigations/<id>/   full case + timeline (internal notes included - you are the investigator)"""

    def get(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case 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("MY_INVESTIGATION", "Case.", d)


class InvestigationNotes(_Inv):
    """POST /employee/relations/investigations/<id>/notes/  {text, is_internal?: true}      GET = timeline"""

    def get(self, request, pk):
        c = self._c(pk)
        return ok("INVESTIGATION_NOTES", "Timeline.", [note_row(n) for n in c.notes.filter(is_active=True)]) if c else err("NOT_FOUND", "Case not found.", 404)

    def post(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        if c.status in ("Closed", "Withdrawn"):
            return err("INVALID_STATE", f"A {c.status.lower()} case cannot receive notes.", 409)
        t = (request.data.get("text") or "").strip()
        if not t:
            return err("VALIDATION", "text is required.")
        internal = str(request.data.get("is_internal", "true")).lower() not in ("0", "false", "no")
        return ok("INVESTIGATION_NOTE_ADDED", "Note added.", note_row(add_note(c, self.me, t, "Note", internal)), 201)


class InvestigationStatus(_Inv):
    """POST /employee/relations/investigations/<id>/status/  {status: In Investigation|Pending Review|Escalated, remarks?}"""

    def post(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        to = request.data.get("status")
        if to not in ("In Investigation", "Pending Review", "Escalated"):
            return err("VALIDATION", "status must be one of: In Investigation, Pending Review, Escalated.")
        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.updated_by = c.status, to, self.actor()
        c.save()
        add_note(c, self.me, f"Status changed {old} -> {to}." + (f" {request.data['remarks']}" if request.data.get("remarks") else ""), "Status", True)
        central_audit(request, self.company, "STATUS", "HR Cases", c.case_no, {"status": old}, {"status": to})
        return ok("INVESTIGATION_STATUS", f"Case moved to {to}.", case_row(c, request))


class InvestigationResolve(_Inv):
    """POST /employee/relations/investigations/<id>/resolve/  {resolution_type, resolution_summary, share_with_complainant?: true}"""

    def post(self, request, pk):
        c = self._c(pk)
        if c is None:
            return err("NOT_FOUND", "Case not found.", 404)
        rt = next((x for x in RESOLVE_TYPES if x.lower() == str(request.data.get("resolution_type") or "").lower()), None)
        rs = (request.data.get("resolution_summary") or "").strip()
        if rt is None:
            return err("VALIDATION", f"resolution_type must be one of: {', '.join(RESOLVE_TYPES)}.")
        if not rs:
            return err("VALIDATION", "resolution_summary is required.")
        if "Resolved" not in TRANSITIONS.get(c.status, set()):
            return err("INVALID_STATE", f"A {c.status.lower()} case cannot be resolved.", 409)
        c.resolution_type, c.resolution_summary, c.status = rt, rs, "Resolved"
        c.resolved_at, c.resolved_by, c.updated_by = timezone.now(), self.actor(), self.actor()
        c.save()
        add_note(c, self.me, f"Resolved: {rt}.", "Resolved", True)
        if str(request.data.get("share_with_complainant", "true")).lower() not in ("0", "false", "no"):
            add_note(c, self.me, "Your case has been resolved. See the resolution summary.", "Update", False)
        central_audit(request, self.company, "RESOLVED", "HR Cases", c.case_no, None, {"resolution_type": rt})
        return ok("INVESTIGATION_RESOLVED", "Case resolved.", case_row(c, request))
