# ============================================================
# Collaboration Calendar   Admin/HR: /api/communication/calendar/    Employee: /employee/communication/calendar/
# GET ?view=month|week|day  ?date=YYYY-MM-DD  (or ?from= & ?to=)  ?sources=meetings,events,holidays,training,interviews
#     ?department=<id>
# Aggregates (read only, nothing duplicated):  Communication.Meeting (recurring series expanded) + People.CompanyEvent
# + Company.Holiday + Training.TrainingSession + Recruitment.InterviewRound.
# ============================================================
from datetime import timedelta

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

from Company.models import Holiday
from People.common import to_date
from People.engagement_common import visible_to
from People.engagement_models import CompanyEvent
from Recruitment.models import InterviewRound
from Training.models import TrainingEnrollment, TrainingSession

from .common import (CommAuthMixin, EmployeeBase, err, iso, local_dt, occurrences, ok)
from .meetings_core import MeetingOps

SOURCES = ["meetings", "events", "holidays", "training", "interviews"]


def view_range(p):
    today = timezone.localdate()
    if p.get("from") or p.get("to"):
        a, b = to_date(p.get("from")), to_date(p.get("to"))
        if not a or not b or b < a or (b - a).days > 400:
            raise ValueError("from and to are required (to >= from, at most 400 days).")
        return "custom", a, b
    view = (p.get("view") or "month").lower()
    d = to_date(p.get("date")) or today
    if view == "month":
        first = d.replace(day=1)
        nxt = (first + timedelta(days=32)).replace(day=1)
        return view, first, nxt - timedelta(days=1)
    if view == "week":
        start = d - timedelta(days=(d.weekday() + 1) % 7)      # Sunday first, like the calendar grid
        return view, start, start + timedelta(days=6)
    if view == "day":
        return view, d, d
    raise ValueError("view must be month, week or day.")


class CalendarMixin(MeetingOps):
    def build(self, request):
        p = request.query_params
        try:
            view, a, b = view_range(p)
        except ValueError as e:
            return err("VALIDATION", str(e))
        want = [s for s in (p.get("sources") or ",".join(SOURCES)).split(",") if s]
        bad = [s for s in want if s not in SOURCES]
        if bad:
            return err("VALIDATION", f"Unknown sources {bad}. Allowed: {', '.join(SOURCES)}")
        c, v, items = self.company(), self.viewer, []
        if "meetings" in want:
            qs = self.visible().filter(status="SCHEDULED")
            if p.get("department"):
                qs = qs.filter(department_id=p["department"])
            parts = {}
            from .models import MeetingParticipant
            for mp in MeetingParticipant.objects.filter(meeting__in=qs, is_active=True):
                parts[(mp.meeting_id, mp.employee_id)] = mp.rsvp
            for m in qs:
                for s, e in occurrences(m, a, b):
                    ls = local_dt(s)
                    items.append({"source": "meeting", "id": m.id, "title": m.title, "start_at": iso(s), "end_at": iso(e),
                                  "date": ls.date().isoformat(), "time_label": ls.strftime("%I:%M %p"), "all_day": False,
                                  "status": "SCHEDULED", "location": m.location, "meeting_link": m.meeting_link,
                                  "recurrence": m.recurrence, "my_rsvp": parts.get((m.id, v.id)) if v else None})
        if "events" in want:
            for ev in CompanyEvent.objects.filter(company=c, is_active=True, is_cancelled=False):
                d = timezone.localtime(ev.start_at).date()
                if a <= d <= b and (self.is_admin or visible_to(ev, v)):
                    items.append({"source": "event", "id": ev.id, "title": ev.title, "start_at": iso(ev.start_at),
                                  "end_at": iso(ev.end_at), "date": d.isoformat(),
                                  "time_label": timezone.localtime(ev.start_at).strftime("%I:%M %p"),
                                  "all_day": False, "status": "SCHEDULED", "location": ev.location,
                                  "meeting_link": ev.meeting_link})
        if "holidays" in want:
            for h in Holiday.objects.filter(company=c, is_active=True, date__gte=a, date__lte=b):
                items.append({"source": "holiday", "id": h.id, "title": h.name, "start_at": None, "end_at": None,
                              "date": h.date.isoformat(), "time_label": None, "all_day": True, "status": h.holiday_type,
                              "location": None, "meeting_link": None})
        if "training" in want:
            qs = TrainingSession.objects.filter(company=c, is_active=True, session_date__gte=a, session_date__lte=b
                                                ).exclude(status="Cancelled")
            if not self.is_admin:
                progs = TrainingEnrollment.objects.filter(company=c, employee=v, is_active=True,
                                                          status__in=["Enrolled", "Completed"]).values_list("program_id", flat=True)
                qs = qs.filter(program_id__in=list(progs))
            for t in qs:
                items.append({"source": "training", "id": t.id, "title": t.title, "start_at": None, "end_at": None,
                              "date": t.session_date.isoformat(),
                              "time_label": t.start_time.strftime("%I:%M %p") if t.start_time else None,
                              "all_day": t.start_time is None, "status": t.status, "location": t.location,
                              "meeting_link": t.meeting_link})
        if "interviews" in want:
            qs = InterviewRound.objects.filter(company=c, is_active=True).exclude(status="Cancelled").select_related("candidate")
            if not self.is_admin:
                qs = qs.filter(interviewer=v)
            for i in qs:
                d = timezone.localtime(i.scheduled_at).date()
                if a <= d <= b:
                    items.append({"source": "interview", "id": i.id, "title": f"{i.round_name}: {i.candidate.name}",
                                  "start_at": iso(i.scheduled_at),
                                  "end_at": iso(i.scheduled_at + timedelta(minutes=i.duration_minutes)),
                                  "date": d.isoformat(), "time_label": timezone.localtime(i.scheduled_at).strftime("%I:%M %p"),
                                  "all_day": False, "status": i.status, "location": i.mode,
                                  "meeting_link": i.meeting_link})
        items.sort(key=lambda x: (x["date"], x["start_at"] or "", x["title"]))
        days = {}
        for it in items:
            days.setdefault(it["date"], []).append(it)
        today = timezone.localdate()
        return ok("COLLABORATION_CALENDAR", "Collaboration calendar.", {
            "view": view, "range": {"from": a.isoformat(), "to": b.isoformat()}, "today": today.isoformat(),
            "title": a.strftime("%B %Y") if view == "month" else f"{a:%d %b} - {b:%d %b %Y}" if view == "week" else a.isoformat(),
            "sources": want, "total": len(items), "days": days, "items": items})


class CalendarAdminView(CalendarMixin, CommAuthMixin, APIView):
    is_admin = True

    @property
    def viewer(self):
        from Employee.models import EmployeeDT
        u = self.request.user
        return u if isinstance(u, EmployeeDT) else None

    def get(self, request):
        return self.build(request)


class CalendarSelfView(CalendarMixin, EmployeeBase, APIView):
    is_admin = False

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

    def get(self, request):
        return self.build(request)
