# ============================================================
# Communication Command Center - overview, broadcast summary, settings, meta (Admin / HR)
# ============================================================
from django.db.models import Count, Sum
from django.utils import timezone
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from Employee.models import Department
from People.engagement_common import live_q
from People.engagement_models import Announcement, AnnouncementView
from People.models import Branch

from .common import (CommAuthMixin, err, employees_qs, get_setting, iso, ok, to_bool,
                     to_int)
from .meetings_core import MeetingOps
from .models import ChannelMessage, ChatChannel, ChatPresence, Meeting
from .common import presence_map


class OverviewViewSet(CommAuthMixin, ViewSet):
    """GET /api/communication/overview/ - the four tabs with counts + headline numbers (computed live)."""

    def list(self, request):
        c, now = self.company(), timezone.now()
        ann = Announcement.objects.filter(company=c, is_active=True)
        channels = ChatChannel.objects.filter(company=c, kind="GROUP", is_active=True)
        ops = MeetingOps()
        ops.company, ops.actor, ops.viewer, ops.is_admin = self.company, self.actor, None, True
        ms = ops.summary(ops.visible(), request)
        today = timezone.localdate()
        msgs_today = ChannelMessage.objects.filter(company=c, is_active=True, is_system=False,
                                                   created_at__date=today).count()
        emp_ids = list(employees_qs(c).filter(is_active=True).values_list("id", flat=True))
        online = sum(1 for p in presence_map(c, emp_ids).values() if p["status"] != "OFFLINE")
        return ok("COMMUNICATION_OVERVIEW", "Communication & Collaboration Command Center.", {
            "title": "Communication & Collaboration Command Center",
            "subtitle": "Real-time workplace chat, corporate announcement feeds, meetings RSVP, and team schedules",
            "tabs": [{"key": "chat", "label": "Workplace Chat & Channels", "count": channels.count()},
                     {"key": "announcements", "label": "Company Announcements & Feed",
                      "count": ann.filter(live_q(now)).count()},
                     {"key": "meetings", "label": "Meetings & Invitations Desk", "count": ms["today"],
                      "badge": f"{ms['today']} Today"},
                     {"key": "calendar", "label": "Collaboration Calendar", "count": None}],
            "stats": {"channels": channels.count(), "private_channels": channels.filter(is_private=True).count(),
                      "messages_today": msgs_today, "employees_online": online,
                      "active_announcements": ann.filter(live_q(now)).count(),
                      "meetings_today": ms["today"], "meetings_upcoming": ms["upcoming"]}})


class AnnouncementFeedViewSet(CommAuthMixin, ViewSet):
    """
    GET /api/communication/announcements/summary/   Broadcast Summary + corporate target groups (computed live).
    The announcement feed itself (list / post / edit / delete / publish / pin / metrics / comments) is the EXISTING
    Employee Engagement API:  /api/people/engagement/announcements/  (admin)  and  /employee/engagement/announcements/ (employee).
    """

    @action(detail=False, methods=["get"])
    def summary(self, request):
        c, now = self.company(), timezone.now()
        base = Announcement.objects.filter(company=c, is_active=True)
        reads = AnnouncementView.objects.filter(company=c, is_active=True, announcement__in=base)
        total_emp = employees_qs(c).filter(is_active=True).count()
        groups = [{"type": "ALL", "id": None, "label": "All Organization (Global Broadcast)", "employees": total_emp}]
        for d in Department.objects.filter(company=c):
            groups.append({"type": "DEPARTMENT", "id": d.id, "label": d.name,
                           "employees": employees_qs(c).filter(is_active=True, department=d).count()})
        for b in Branch.objects.filter(company=c, is_active=True):
            groups.append({"type": "BRANCH", "id": b.id, "label": b.name,
                           "employees": employees_qs(c).filter(is_active=True, people_profile__branch=b).count()})
        return ok("BROADCAST_SUMMARY", "Broadcast summary.", {
            "total_active_announcements": base.filter(live_q(now)).count(),
            "scheduled_for_future": base.filter(status="SCHEDULED", publish_at__gt=now).count(),
            "draft_announcements": base.filter(status="DRAFT").count(),
            "archived_announcements": base.filter(status="ARCHIVED").count(),
            "total_employee_reads": reads.aggregate(s=Sum("view_count"))["s"] or 0,
            "unique_readers": reads.values("employee").distinct().count(),
            "target_groups": groups,
            "feed_endpoints": {"admin": "/api/people/engagement/announcements/",
                               "employee": "/employee/engagement/announcements/"}})


class SettingsView(CommAuthMixin, APIView):
    """GET /api/communication/settings/ | PUT|PATCH /api/communication/settings/  (company rules)"""
    FIELDS = {"allow_employee_channels": ("bool", None), "presence_timeout_minutes": ("int", (1, 120)),
              "message_edit_window_minutes": ("int", (0, 1440)), "max_attachment_mb": ("int", (1, 50)),
              "default_meeting_minutes": ("int", (5, 480)), "block_on_conflict": ("bool", None)}

    def row(self, s):
        return {k: getattr(s, k) for k in self.FIELDS} | {"updated_at": iso(s.updated_at), "updated_by": s.updated_by}

    def get(self, request):
        return ok("COMMUNICATION_SETTINGS", "Settings.", self.row(get_setting(self.company())))

    def put(self, request):
        s = get_setting(self.company())
        try:
            for k, (kind, rng) in self.FIELDS.items():
                if k not in request.data:
                    continue
                if kind == "bool":
                    setattr(s, k, to_bool(request.data[k]))
                else:
                    v = to_int(request.data[k])
                    if v is None or not rng[0] <= v <= rng[1]:
                        raise ValueError(f"{k} must be between {rng[0]} and {rng[1]}.")
                    setattr(s, k, v)
        except ValueError as e:
            return err("VALIDATION", str(e))
        s.updated_by = self.actor()
        s.save()
        return ok("COMMUNICATION_SETTINGS_SAVED", "Settings saved.", self.row(s))

    patch = put


class MetaViewSet(CommAuthMixin, ViewSet):
    def list(self, request):
        c = self.company()
        return ok("COMMUNICATION_META", "Dropdown values.", {
            "meeting_types": [{"code": k, "label": v} for k, v in Meeting.TYPES],
            "recurrence": [{"code": k, "label": v} for k, v in Meeting.RECURRENCE],
            "rsvp_responses": [{"code": k, "label": v} for k, v in (("ACCEPTED", "Accept"), ("DECLINED", "Decline"),
                                                                    ("TENTATIVE", "Maybe"))],
            "presence_statuses": ["ONLINE", "AWAY", "BUSY", "OFFLINE"],
            "calendar_sources": ["meetings", "events", "holidays", "training", "interviews"],
            "calendar_views": ["month", "week", "day"],
            "departments": list(Department.objects.filter(company=c).values("id", "name")),
            "branches": list(Branch.objects.filter(company=c, is_active=True).values("id", "name")),
            "settings": SettingsView().row(get_setting(c))})
