# ============================================================
# Legal Cases (legal notices, labour tribunal, industrial disputes)     /api/relations/legal-cases/
# ============================================================
from decimal import Decimal

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

from .common import ERCase, LegalCase, RelCrud, central_audit, emp_by_code, err, legal_row, next_no, norm, ok, to_date, to_decimal
from .views_cases import NumberedCreate
from .views_discipline import find_case

CLOSING = ("Settled", "Won", "Lost", "Withdrawn", "Closed")


class LegalCaseViewSet(NumberedCreate, RelCrud):
    """
    CRUD   /api/relations/legal-cases/            ?status= ?case_type= ?employee=<code> ?active=true ?hearing_from= ?hearing_to= ?search=
    POST   {case_type: Legal Notice|Labour Tribunal|Industrial Dispute|Court Case|Arbitration|Other, title, employee_code? | claimant?, forum?, court_case_number?,
            case?, filed_on?, next_hearing_date?, counsel_name?, claim_amount?, notes?}
    POST   /<id>/status/  {status, outcome?}      Open | Under Review | Hearing Scheduled | Settled | Won | Lost | Withdrawn | Closed  (closing needs outcome)
    POST   /<id>/reopen/  {remarks}
    GET    /api/relations/legal-cases/summary/    banner of the tab + upcoming hearings
    """
    model, code, module_label, ref_field = LegalCase, "LEGAL_CASE", "Legal Cases", "legal_id"
    select = ("employee", "case")
    search_fields = ("title", "legal_no", "claimant", "court_case_number", "forum", "employee__name", "employee__employee_code")
    permission_action_map = {"status": "edit", "reopen": "approve", "summary": "view"}

    def build(self, l):
        return legal_row(l, self.request)

    def filter(self, qs, p):
        qs = super().filter(qs, p)
        if p.get("case_type"):
            qs = qs.filter(case_type__iexact=p["case_type"])
        if str(p.get("active", "")).lower() in ("1", "true", "yes"):
            qs = qs.filter(status__in=LegalCase.ACTIVE)
        if p.get("hearing_from"):
            qs = qs.filter(next_hearing_date__gte=to_date(p["hearing_from"]))
        if p.get("hearing_to"):
            qs = qs.filter(next_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 apply(self, l, d, creating):
        co, today = self.company(), timezone.localdate()
        if not creating and l.status in CLOSING:
            raise ValueError(f"A {l.status.lower()} legal case cannot be edited. Reopen it first.")
        t = next((x for x in LegalCase.TYPES if x.lower() == str(d.get("case_type") or l.case_type or "").lower()), None)
        if t is None:
            raise ValueError(f"case_type must be one of: {', '.join(LegalCase.TYPES)}.")
        l.case_type = t
        title = (d.get("title") or l.title or "").strip()
        if not title:
            raise ValueError("title is required.")
        l.title = title[:300]
        if "employee_code" in d:
            l.employee = emp_by_code(co, d["employee_code"], required=False) if d["employee_code"] else None
        if "claimant" in d:
            l.claimant = d["claimant"]
        if not l.employee_id and not (l.claimant or "").strip():
            raise ValueError("Provide employee_code or claimant.")
        for k in ("forum", "counsel_name", "notes", "outcome"):
            if k in d:
                setattr(l, k, d[k])
        if "court_case_number" in d:
            l.court_case_number = (d["court_case_number"] or "").strip() or None
        if "case" in d:
            l.case = find_case(co, d["case"])
        if "filed_on" in d:
            f = to_date(d["filed_on"])
            if f and f > today:
                raise ValueError("filed_on cannot be in the future.")
            l.filed_on = f
        if "next_hearing_date" in d:
            h = to_date(d["next_hearing_date"])
            if h and h < today and h != l.next_hearing_date:
                raise ValueError("next_hearing_date cannot be in the past.")
            if h and l.filed_on and h < l.filed_on:
                raise ValueError("next_hearing_date cannot be before filed_on.")
            l.next_hearing_date = h
        if "claim_amount" in d:
            a = to_decimal(d["claim_amount"])
            if a is not None and a < 0:
                raise ValueError("claim_amount cannot be negative.")
            l.claim_amount = a
        # duplicates: same court number, or same type + title + claimant
        q = LegalCase.objects.all()
        if l.pk:
            q = q.exclude(pk=l.pk)
        if l.court_case_number:
            self.dup(q.filter(court_case_number__iexact=l.court_case_number), f"Duplicate: court case number '{l.court_case_number}' is already registered.")
        for o in q.filter(company=co, is_active=True, case_type=l.case_type):
            if norm(o.title) == norm(l.title) and norm(o.claimant or (o.employee.name if o.employee_id else "")) == norm(l.claimant or (l.employee.name if l.employee_id else "")):
                raise ValueError(f"Duplicate: the same legal matter is already registered ({o.legal_no}).")
        if creating:
            l.legal_no = next_no(LegalCase, co, "legal_no", f"LEG-{today.year}-", 2)

    def before_delete(self, l):
        if l.status not in ("Open", "Withdrawn"):
            raise ValueError("Only Open or Withdrawn legal cases can be deleted.")
        if l.documents.filter(is_active=True).exists():
            raise ValueError("Linked vault documents exist; remove them first.")

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

    @action(detail=True, methods=["post"], url_path="status")
    def status(self, request, pk=None):
        l = self._l(pk)
        if l is None:
            return err("NOT_FOUND", "Record not found.", 404)
        to = request.data.get("status")
        if to not in LegalCase.STATUS:
            return err("VALIDATION", f"status must be one of: {', '.join(LegalCase.STATUS)}.")
        if l.status in CLOSING:
            return err("INVALID_STATE", f"A {l.status.lower()} legal case cannot change status. Reopen it first.", 409)
        if to == "Hearing Scheduled" and not l.next_hearing_date:
            return err("VALIDATION", "Set next_hearing_date before scheduling a hearing.")
        out = (request.data.get("outcome") or "").strip()
        if to in CLOSING:
            if not out:
                return err("VALIDATION", "outcome is required when closing a legal case.")
            l.outcome, l.closed_on = out, timezone.localdate()
        old, l.status, l.updated_by = l.status, to, self.actor()
        l.save()
        central_audit(request, self.company(), "STATUS", self.module_label, l.legal_no, {"status": old}, {"status": to})
        return ok("LEGAL_CASE_STATUS", f"Legal case moved to {to}.", legal_row(l, request))

    @action(detail=True, methods=["post"], url_path="reopen")
    def reopen(self, request, pk=None):
        l = self._l(pk)
        if l is None:
            return err("NOT_FOUND", "Record not found.", 404)
        if l.status not in CLOSING:
            return err("INVALID_STATE", "Only a closed legal case can be reopened.", 409)
        if not (request.data.get("remarks") or "").strip():
            return err("VALIDATION", "remarks are required to reopen.")
        l.status, l.closed_on, l.updated_by = "Under Review", None, self.actor()
        l.save()
        central_audit(request, self.company(), "REOPENED", self.module_label, l.legal_no, None, {"remarks": request.data["remarks"]})
        return ok("LEGAL_CASE_REOPENED", "Legal case reopened.", legal_row(l, request))

    @action(detail=False, methods=["get"], url_path="summary")
    def summary(self, request):
        co, t = self.company(), timezone.localdate()
        qs = LegalCase.objects.filter(company=co, is_active=True)
        act = qs.filter(status__in=LegalCase.ACTIVE)
        n = act.count()
        name = getattr(co, "Registered_Company_Name", None) or "the company"
        msg = f"No active legal or industrial dispute claims pending against {name}." if n == 0 else f"{n} active legal or industrial dispute claim(s) pending against {name}."
        total = sum((a.claim_amount or Decimal(0)) for a in act)
        up = [{"id": x.id, "legal_id": x.legal_no, "title": x.title, "next_hearing_date": x.next_hearing_date.isoformat()} for x in act.filter(next_hearing_date__gte=t).order_by("next_hearing_date")[:5]]
        return ok("LEGAL_SUMMARY", msg, {"message": msg, "active": n, "total": qs.count(), "active_claim_amount": float(total),
                                         "by_status": {s: qs.filter(status=s).count() for s in LegalCase.STATUS}, "upcoming_hearings": up})
