# ============================================================
# Summary / Meta / Settings       /api/relations/summary|meta|settings/
# ============================================================
from datetime import timedelta

from django.db.models import Avg, F, ExpressionWrapper, DurationField
from django.utils import timezone
from rest_framework.views import APIView

from Employee.models import EmployeeDT

from .common import (CATEGORIES, CASE_STATUS, OPEN_CASE, SEVERITIES, DisciplinaryAction, ERCase, LegalCase, RelAuthMixin, RESOLUTION_TYPES, WarningLetter, emp_by_code,
                     err, get_setting, ok, resolve_actor_role, setting_row, to_int)


class SummaryView(RelAuthMixin, APIView):
    """GET /api/relations/summary/   KPI cards for the whole workspace"""
    permission_action = "view"

    def get(self, request):
        co, t = self.company(), timezone.localdate()
        cases = ERCase.objects.filter(company=co, is_active=True)
        open_ = cases.filter(status__in=OPEN_CASE)
        done = cases.filter(resolved_at__isnull=False)
        days = [(c.resolved_at - c.opened_at).total_seconds() / 86400 for c in done]
        hearings = [{"type": "Disciplinary", "id": d.id, "employee": d.employee.name, "date": d.hearing_date.isoformat()}
                    for d in DisciplinaryAction.objects.filter(company=co, is_active=True, status="Hearing Scheduled", hearing_date__gte=t, hearing_date__lte=t + timedelta(days=14)).select_related("employee")]
        hearings += [{"type": "Legal", "id": l.id, "title": l.title, "date": l.next_hearing_date.isoformat()}
                     for l in LegalCase.objects.filter(company=co, is_active=True, status__in=LegalCase.ACTIVE, next_hearing_date__gte=t, next_hearing_date__lte=t + timedelta(days=14))]
        return ok("RELATIONS_SUMMARY", "Employee relations summary.", {
            "cases_total": cases.count(), "cases_open": open_.count(), "cases_overdue": open_.filter(target_date__lt=t).count(),
            "cases_by_status": {s: cases.filter(status=s).count() for s in CASE_STATUS},
            "open_by_severity": {s: open_.filter(severity=s).count() for s in SEVERITIES},
            "open_by_category": {c: open_.filter(category=c).count() for c in CATEGORIES if open_.filter(category=c).exists()},
            "avg_resolution_days": round(sum(days) / len(days), 1) if days else None,
            "warnings_issued_this_year": WarningLetter.objects.filter(company=co, is_active=True, status__in=["Issued", "Acknowledged"], issued_on__year=t.year).count(),
            "warnings_awaiting_acknowledgement": WarningLetter.objects.filter(company=co, is_active=True, status="Issued").count(),
            "disciplinary_in_progress": DisciplinaryAction.objects.filter(company=co, is_active=True).exclude(status__in=["Closed", "Cancelled", "Decision Issued"]).count(),
            "legal_active": LegalCase.objects.filter(company=co, is_active=True, status__in=LegalCase.ACTIVE).count(),
            "upcoming_hearings_14_days": sorted(hearings, key=lambda x: x["date"])})


class MetaView(RelAuthMixin, APIView):
    """GET /api/relations/meta/   dropdown values for every form"""
    permission_action = "view"

    def get(self, request):
        return ok("RELATIONS_META", "Dropdowns.", {
            "tabs": ["hr-cases", "grievances", "complaints", "disciplinary-actions", "warnings", "legal-cases", "case-documents"],
            "categories": CATEGORIES, "severities": SEVERITIES, "case_statuses": CASE_STATUS, "sources": [k for k, _ in ERCase.SOURCES],
            "resolution_types": RESOLUTION_TYPES, "disciplinary_types": DisciplinaryAction.TYPES, "disciplinary_statuses": DisciplinaryAction.STATUS,
            "disciplinary_outcomes": DisciplinaryAction.OUTCOMES, "warning_levels": WarningLetter.LEVELS, "warning_statuses": WarningLetter.STATUS,
            "legal_types": LegalCase.TYPES, "legal_statuses": LegalCase.STATUS, "document_types": ["Evidence", "Statement", "Notice", "Letter", "Order", "Report", "Other"],
            "confidentiality_levels": ["Confidential", "Restricted"], "complaint_sub_categories": ["POSH", "Code of Conduct"]})


class SettingsView(RelAuthMixin, APIView):
    """
    GET /api/relations/settings/
    PUT /api/relations/settings/   COMPANY ADMIN ONLY (it decides who may open the vault)
        {hr_head_code, legal_counsel_code, icc_presiding_officer_code, icc_meeting_frequency, vault_members_codes:[..], hearing_notice_days, warning_valid_months}
    """
    def get(self, request):
        return ok("RELATIONS_SETTINGS", "Settings.", setting_row(get_setting(self.company()), request))

    def put(self, request):
        if resolve_actor_role(request.user) != "admin":
            return err("FORBIDDEN", "Only the Company Admin can change these settings.", 403)
        co, d = self.company(), request.data
        s = get_setting(co)
        try:
            for k, f in (("hr_head_code", "hr_head"), ("legal_counsel_code", "legal_counsel"), ("icc_presiding_officer_code", "icc_presiding_officer")):
                if k in d:
                    setattr(s, f, emp_by_code(co, d[k]) if d[k] else None)
            if "icc_meeting_frequency" in d:
                if d["icc_meeting_frequency"] not in dict(s.FREQ):
                    raise ValueError(f"icc_meeting_frequency must be one of: {', '.join(dict(s.FREQ))}.")
                s.icc_meeting_frequency = d["icc_meeting_frequency"]
            if "hearing_notice_days" in d:
                n = to_int(d["hearing_notice_days"])
                if n is None or not 0 <= n <= 30:
                    raise ValueError("hearing_notice_days must be between 0 and 30.")
                s.hearing_notice_days = n
            if "warning_valid_months" in d:
                n = to_int(d["warning_valid_months"])
                if n is None or not 1 <= n <= 60:
                    raise ValueError("warning_valid_months must be between 1 and 60.")
                s.warning_valid_months = n
            members = None
            if "vault_members_codes" in d:
                if not isinstance(d["vault_members_codes"], list):
                    raise ValueError("vault_members_codes must be a list.")
                members = [emp_by_code(co, c) for c in d["vault_members_codes"]]
        except ValueError as e:
            return err("VALIDATION", str(e))
        s.updated_by = self.actor()
        s.save()
        if members is not None:
            s.vault_members.set(members)
        from .common import central_audit
        central_audit(request, co, "UPDATED", "Employee Relations", "settings", None, setting_row(s))
        return ok("RELATIONS_SETTINGS_UPDATED", "Settings updated.", setting_row(s, request))

    patch = put
