# ============================================================
# Disciplinary Actions (hearings & inquiries) and Warnings (formal warning letters)
#   /api/relations/disciplinary/   /api/relations/warnings/
# Warning letters are produced by the EXISTING People.letters engine (template DISCIPLINARY_WARNING + PDF).
# ============================================================
import calendar
from datetime import datetime, timedelta

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

from People.letters import _Safe, build_variables, issue_letter, resolve_template

from .common import (DisciplinaryAction, ERCase, RelCrud, WarningLetter, add_note, central_audit, disc_row, emp_by_code, err, get_setting, letter_row, next_no,
                     norm, ok, to_date, warning_row)
from .views_cases import NumberedCreate


def add_months(d, n):
    m = d.month - 1 + n
    y, m = d.year + m // 12, m % 12 + 1
    return d.replace(year=y, month=m, day=min(d.day, calendar.monthrange(y, m)[1]))


def find_case(company, ref):
    if ref in (None, ""):
        return None
    q = ERCase.objects.filter(company=company, is_active=True)
    c = q.filter(pk=int(ref)).first() if str(ref).isdigit() else q.filter(case_no__iexact=str(ref)).first()
    if c is None:
        raise ValueError(f"Case '{ref}' not found.")
    return c


# ---------------- disciplinary actions ----------------
class DisciplinaryViewSet(RelCrud):
    """
    CRUD   /api/relations/disciplinary/            ?status= ?action_type= ?employee=<code> ?case=<id|CASE-01> ?hearing_from= ?hearing_to= ?search=
    POST   {employee_code, action_type, charge, case?, notice_served_on?, hearing_date?, hearing_time?, hearing_location?, committee_codes?:[..]}
    POST   /<id>/schedule-hearing/ {hearing_date, hearing_time?, hearing_location?, committee_codes?}     -> Hearing Scheduled (needs the notice period)
    POST   /<id>/record-hearing/   {minutes}                                                              -> Hearing Held
    POST   /<id>/decide/           {outcome: Penalty Imposed|Warning Issued|Exonerated|Dismissed, penalty?, decision_date?}   -> Decision Issued
    POST   /<id>/appeal/  /close/  /cancel/ {reason}
    """
    model, code, module_label = DisciplinaryAction, "DISCIPLINARY", "Disciplinary Actions"
    select = ("employee", "case", "employee__department")
    search_fields = ("charge", "employee__name", "employee__employee_code", "case__case_no")
    permission_action_map = {"schedule_hearing": "edit", "record_hearing": "edit", "decide": "approve", "appeal": "edit", "close": "approve", "cancel": "edit"}
    LOCKED = ("Decision Issued", "Appealed", "Closed", "Cancelled")

    def build(self, d):
        return disc_row(d, self.request)

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("action_type"):
            qs = qs.filter(action_type__iexact=p["action_type"])
        if p.get("case"):
            qs = qs.filter(case_id=int(p["case"])) if str(p["case"]).isdigit() else qs.filter(case__case_no__iexact=p["case"])
        if p.get("hearing_from"):
            qs = qs.filter(hearing_date__gte=to_date(p["hearing_from"]))
        if p.get("hearing_to"):
            qs = qs.filter(hearing_date__lte=to_date(p["hearing_to"]))
        return qs

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

    def _hearing(self, d, data, creating=False):
        co, st = self.company(), get_setting(self.company())
        if "notice_served_on" in data or creating:
            d.notice_served_on = to_date(data.get("notice_served_on")) or (timezone.localdate() if creating else d.notice_served_on)
        if "hearing_date" in data:
            d.hearing_date = to_date(data["hearing_date"])
        if "hearing_time" in data:
            try:
                d.hearing_time = datetime.strptime(str(data["hearing_time"])[:5], "%H:%M").time() if data["hearing_time"] else None
            except ValueError:
                raise ValueError("hearing_time must be HH:MM (24h).")
        if "hearing_location" in data:
            d.hearing_location = data["hearing_location"]
        if d.hearing_date:
            if not d.notice_served_on:
                raise ValueError("notice_served_on is required before a hearing can be fixed.")
            if d.hearing_date < d.notice_served_on + timedelta(days=st.hearing_notice_days):
                raise ValueError(f"The hearing must be at least {st.hearing_notice_days} day(s) after the notice date "
                                 f"({(d.notice_served_on + timedelta(days=st.hearing_notice_days)).isoformat()} or later).")
        if "committee_codes" in data:
            codes = data["committee_codes"]
            if not isinstance(codes, list):
                raise ValueError("committee_codes must be a list of employee codes.")
            members = [emp_by_code(co, c) for c in codes]
            if any(m.pk == d.employee_id for m in members):
                raise ValueError("The employee under inquiry cannot sit on the committee.")
            d._members = members

    def apply(self, d, data, creating):
        co = self.company()
        if not creating and d.status in self.LOCKED:
            raise ValueError(f"A {d.status.lower()} action cannot be edited.")
        if creating:
            d.employee = emp_by_code(co, data.get("employee_code"))
            d.case = find_case(co, data.get("case"))
            if d.case and d.case.employee_id != d.employee_id:
                raise ValueError(f"Case {d.case.case_no} is about a different employee.")
        t = next((x for x in DisciplinaryAction.TYPES if x.lower() == str(data.get("action_type") or d.action_type or "").lower()), None)
        if t is None:
            raise ValueError(f"action_type must be one of: {', '.join(DisciplinaryAction.TYPES)}.")
        d.action_type = t
        ch = (data.get("charge") or d.charge or "").strip()
        if not ch:
            raise ValueError("charge is required (the allegation put to the employee).")
        d.charge = ch
        self._hearing(d, data, creating)
        if creating:
            d.status = "Hearing Scheduled" if d.hearing_date else "Notice Issued"
        q = DisciplinaryAction.objects.filter(employee=d.employee, action_type=d.action_type, hearing_date=d.hearing_date, case=d.case).exclude(status="Cancelled")
        if d.pk:
            q = q.exclude(pk=d.pk)
        self.dup(q, "Duplicate: the same action for this employee, case and hearing date already exists.")

    def after_save(self, d, creating):
        if hasattr(d, "_members"):
            d.committee.set(d._members)
        if creating and d.case_id:
            add_note(d.case, self.request.user, f"Disciplinary action raised: {d.action_type}.", "Update", True)

    def before_delete(self, d):
        if d.status not in ("Notice Issued", "Cancelled"):
            raise ValueError("Only actions at the notice stage (or cancelled ones) can be deleted.")
        if d.documents.filter(is_active=True).exists() or d.warnings.filter(is_active=True).exists():
            raise ValueError("Linked documents / warnings exist; remove them first.")

    def _d(self, pk):
        return self.scope().filter(pk=pk, is_active=True).first()

    def _save(self, d, request, code, msg, event):
        d.updated_by = self.actor()
        d.save()
        central_audit(request, self.company(), event, self.module_label, f"#{d.id} {d.employee.employee_code}", None, {"status": d.status, "outcome": d.outcome})
        return ok(code, msg, disc_row(d, request))

    @action(detail=True, methods=["post"], url_path="schedule-hearing")
    def schedule_hearing(self, request, pk=None):
        d = self._d(pk)
        if d is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if d.status not in ("Notice Issued", "Hearing Scheduled"):
            return err("INVALID_STATE", f"A hearing cannot be scheduled while the action is {d.status}.", 409)
        if not request.data.get("hearing_date"):
            return err("VALIDATION", "hearing_date is required.")
        try:
            self._hearing(d, request.data)
        except ValueError as e:
            return err("VALIDATION", str(e))
        d.status = "Hearing Scheduled"
        if hasattr(d, "_members"):
            d.committee.set(d._members)
        return self._save(d, request, "DISCIPLINARY_SCHEDULED", "Hearing scheduled.", "HEARING_SCHEDULED")

    @action(detail=True, methods=["post"], url_path="record-hearing")
    def record_hearing(self, request, pk=None):
        d = self._d(pk)
        if d is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if d.status != "Hearing Scheduled":
            return err("INVALID_STATE", f"Only a scheduled hearing can be recorded (this one is {d.status}).", 409)
        if d.hearing_date and d.hearing_date > timezone.localdate():
            return err("INVALID_STATE", f"The hearing is on {d.hearing_date.isoformat()}; it cannot be recorded before it takes place.", 409)
        m = (request.data.get("minutes") or "").strip()
        if not m:
            return err("VALIDATION", "minutes are required.")
        d.minutes, d.status = m, "Hearing Held"
        return self._save(d, request, "DISCIPLINARY_HEARING_HELD", "Hearing recorded.", "HEARING_HELD")

    @action(detail=True, methods=["post"], url_path="decide")
    def decide(self, request, pk=None):
        d = self._d(pk)
        if d is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if d.status != "Hearing Held":
            return err("INVALID_STATE", "A decision can be issued only after the hearing is held (natural justice: notice -> hearing -> decision).", 409)
        oc = next((x for x in DisciplinaryAction.OUTCOMES if x.lower() == str(request.data.get("outcome") or "").lower() and x != "Pending"), None)
        if oc is None:
            return err("VALIDATION", "outcome must be one of: Penalty Imposed, Warning Issued, Exonerated, Dismissed.")
        if oc == "Penalty Imposed" and not (request.data.get("penalty") or "").strip():
            return err("VALIDATION", "penalty is required when the outcome is Penalty Imposed.")
        try:
            dd = to_date(request.data.get("decision_date")) or timezone.localdate()
        except ValueError as e:
            return err("VALIDATION", str(e))
        d.outcome, d.penalty, d.decision_date, d.decided_by, d.status = oc, request.data.get("penalty"), dd, self.actor(), "Decision Issued"
        return self._save(d, request, "DISCIPLINARY_DECIDED", "Decision issued.", "DECISION")

    def _simple(self, request, pk, frm, to, code, msg, event, need=None):
        d = self._d(pk)
        if d is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if d.status not in frm:
            return err("INVALID_STATE", f"This action is {d.status}; allowed only from: {', '.join(frm)}.", 409)
        if need and not (request.data.get(need) or "").strip():
            return err("VALIDATION", f"{need} is required.")
        d.status = to
        if need:
            d.minutes = ((d.minutes or "") + f"\n[{to}] {request.data[need]}").strip()
        return self._save(d, request, code, msg, event)

    @action(detail=True, methods=["post"], url_path="appeal")
    def appeal(self, request, pk=None):
        return self._simple(request, pk, ("Decision Issued",), "Appealed", "DISCIPLINARY_APPEALED", "Appeal recorded.", "APPEAL", "reason")

    @action(detail=True, methods=["post"], url_path="close")
    def close(self, request, pk=None):
        return self._simple(request, pk, ("Decision Issued", "Appealed"), "Closed", "DISCIPLINARY_CLOSED", "Action closed.", "CLOSED")

    @action(detail=True, methods=["post"], url_path="cancel")
    def cancel(self, request, pk=None):
        return self._simple(request, pk, ("Notice Issued", "Hearing Scheduled"), "Cancelled", "DISCIPLINARY_CANCELLED", "Action cancelled.", "CANCELLED", "reason")


# ---------------- warnings ----------------
def preview_letter(w, request=None):
    """Rendered text of the letter (without saving) - used for drafts."""
    subj, body = resolve_template(w.company, "DISCIPLINARY_WARNING")
    v = build_variables(w.employee, {"warning_level": w.level, "incident_date": w.incident_date or "-", "warning_reason": w.reason})
    return {"letter_id": None, "letter_no": None, "subject": subj.format_map(_Safe(v)), "body": body.format_map(_Safe(v)), "pdf_url": None}


class WarningViewSet(NumberedCreate, RelCrud):
    """
    CRUD   /api/relations/warnings/              ?status= ?level= ?employee=<code> ?case= ?active=true ?date_from= ?date_to= ?search=
    POST   {employee_code, level: Verbal Warning|Written Warning|Final Written Warning|Show Cause Notice, reason, incident_date?, case?, disciplinary_id?, issue?: true}
           issue=true (default) generates the letter + PDF at once; issue=false saves a Draft.
    POST   /<id>/issue/  (Draft -> Issued)      POST /<id>/withdraw/ {reason}
    GET    /<id>/letter/                        [View Letter] subject + body + pdf_url (draft = preview)
    """
    model, code, module_label, ref_field = WarningLetter, "WARNING", "Warnings", "warning_id"
    select = ("employee", "case", "letter", "employee__department")
    search_fields = ("reason", "warning_no", "employee__name", "employee__employee_code")
    permission_action_map = {"issue": "approve", "withdraw": "approve", "letter": "view"}

    def build(self, w):
        return warning_row(w, self.request)

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("level"):
            qs = qs.filter(level__iexact=p["level"])
        if p.get("case"):
            qs = qs.filter(case_id=int(p["case"])) if str(p["case"]).isdigit() else qs.filter(case__case_no__iexact=p["case"])
        if p.get("date_from"):
            qs = qs.filter(issued_on__gte=to_date(p["date_from"]))
        if p.get("date_to"):
            qs = qs.filter(issued_on__lte=to_date(p["date_to"]))
        if str(p.get("active", "")).lower() in ("1", "true", "yes"):
            qs = qs.filter(status__in=["Issued", "Acknowledged"], valid_until__gte=timezone.localdate())
        return qs

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

    def apply(self, w, d, creating):
        co, today = self.company(), timezone.localdate()
        if not creating and w.status != "Draft":
            raise ValueError(f"A {w.status.lower()} warning cannot be edited.")
        if creating:
            w.employee = emp_by_code(co, d.get("employee_code"))
            w.case = find_case(co, d.get("case"))
            if w.case and w.case.employee_id != w.employee_id:
                raise ValueError(f"Case {w.case.case_no} is about a different employee.")
            if d.get("disciplinary_id"):
                da = DisciplinaryAction.objects.filter(company=co, is_active=True, pk=d["disciplinary_id"]).first()
                if da is None or da.employee_id != w.employee_id:
                    raise ValueError("disciplinary_id not found for this employee.")
                w.disciplinary = da
        lv = next((x for x in WarningLetter.LEVELS if x.lower() == str(d.get("level") or w.level or "").lower()), None)
        if lv is None:
            raise ValueError(f"level must be one of: {', '.join(WarningLetter.LEVELS)}.")
        w.level = lv
        rs = (d.get("reason") or w.reason or "").strip()
        if not rs:
            raise ValueError("reason is required.")
        w.reason = rs
        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.")
            w.incident_date = i
        q = WarningLetter.objects.filter(employee=w.employee, level=w.level, incident_date=w.incident_date).exclude(status="Withdrawn")
        if w.pk:
            q = q.exclude(pk=w.pk)
        for o in q.filter(company=co, is_active=True):
            if norm(o.reason) == norm(w.reason):
                raise ValueError(f"Duplicate: the same warning was already recorded for this employee ({o.warning_no}).")
        if creating:
            w.warning_no = next_no(WarningLetter, co, "warning_no", f"WRN-{today.year}-", 2)
            w._issue_now = d.get("issue", True) not in (False, "false", "False", "0", 0)

    def _issue(self, w):
        today = timezone.localdate()
        try:
            letter = issue_letter(w.company, w.employee, "DISCIPLINARY_WARNING", self.actor(),
                                  {"warning_level": w.level, "incident_date": w.incident_date or "-", "warning_reason": w.reason})
        except Exception as e:
            raise ValueError(f"Could not generate the warning letter: {str(e)[:150]}")
        w.letter, w.status, w.issued_on, w.issued_by = letter, "Issued", today, self.actor()
        w.valid_until = add_months(today, get_setting(w.company).warning_valid_months)

    def after_save(self, w, creating):
        if creating and getattr(w, "_issue_now", False):
            self._issue(w)
            w.save()
        if creating and w.case_id:
            add_note(w.case, self.request.user, f"{w.level} {w.warning_no} recorded ({w.status}).", "Update", True)

    def before_delete(self, w):
        if w.status not in ("Draft", "Withdrawn"):
            raise ValueError("Only Draft or Withdrawn warnings can be deleted. Withdraw an issued warning instead.")

    def _w(self, pk):
        return self.scope().filter(pk=pk, is_active=True).first()

    @action(detail=True, methods=["post"], url_path="issue")
    def issue(self, request, pk=None):
        w = self._w(pk)
        if w is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if w.status != "Draft":
            return err("INVALID_STATE", f"Only Draft warnings can be issued (this one is {w.status}).", 409)
        try:
            self._issue(w)
        except ValueError as e:
            return err("ERROR", str(e), 500)
        w.updated_by = self.actor()
        w.save()
        central_audit(request, self.company(), "ISSUED", self.module_label, w.warning_no, None, {"employee": w.employee.employee_code, "level": w.level})
        return ok("WARNING_ISSUED", "Warning issued.", warning_row(w, request, True))

    @action(detail=True, methods=["post"], url_path="withdraw")
    def withdraw(self, request, pk=None):
        w = self._w(pk)
        if w is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if w.status not in ("Issued", "Acknowledged"):
            return err("INVALID_STATE", f"Only issued warnings can be withdrawn (this one is {w.status}).", 409)
        r = (request.data.get("reason") or "").strip()
        if not r:
            return err("VALIDATION", "reason is required.")
        w.status, w.withdrawn_reason, w.updated_by = "Withdrawn", r, self.actor()
        w.save()
        central_audit(request, self.company(), "WITHDRAWN", self.module_label, w.warning_no, None, {"reason": r})
        return ok("WARNING_WITHDRAWN", "Warning withdrawn.", warning_row(w, request))

    @action(detail=True, methods=["get"], url_path="letter")
    def letter(self, request, pk=None):
        w = self._w(pk)
        if w is None:
            return err("NOT_FOUND", "Record not found.", 404)
        return ok("WARNING_LETTER", "Warning letter." if w.letter_id else "Draft preview (not yet issued).",
                  letter_row(w.letter, request) if w.letter_id else preview_letter(w, request))
