# ============================================================
# ADDITIVE: shared helpers for Employee Engagement (admin + employee side)
# ============================================================
import os
from datetime import date, datetime, timedelta

from django.db.models import Count, Q, Sum
from django.utils import timezone
from django.utils.dateparse import parse_datetime

from Employee.models import Department, EmployeeDT

from .common import dept_name, employees_qs, iso, to_date
from .engagement_models import (Announcement, AnnouncementComment, AnnouncementReaction, AnnouncementView,
                                EventRsvp, Survey, SurveyAnswer, SurveyResponse)
from .models import Branch

BADGES = ["Innovation Hero", "Team Player", "Customer Champion", "Above & Beyond", "Problem Solver",
          "Mentor of the Month", "Rising Star", "Culture Ambassador"]
ALLOWED_IMG = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
MAX_IMG_MB = 5


def choices_of(model_choices):
    return [{"code": c, "label": l} for c, l in model_choices]


def to_dt(value):
    """ISO datetime or YYYY-MM-DD -> aware datetime (Asia/Kolkata)."""
    if value in (None, ""):
        return None
    if isinstance(value, datetime):
        dt = value
    elif isinstance(value, date):
        dt = datetime(value.year, value.month, value.day)
    else:
        s = str(value).strip().replace("Z", "+00:00")
        dt = parse_datetime(s)
        if dt is None:
            d = to_date(s[:10])
            dt = datetime(d.year, d.month, d.day, 9, 0)
    return timezone.make_aware(dt) if timezone.is_naive(dt) else dt


def check_image(f):
    if os.path.splitext(f.name)[1].lower() not in ALLOWED_IMG:
        raise ValueError("Image must be png, jpg, jpeg, webp or gif.")
    if f.size > MAX_IMG_MB * 1024 * 1024:
        raise ValueError(f"Image too large (max {MAX_IMG_MB} MB).")


def media_url(request, f):
    if not f:
        return None
    try:
        return request.build_absolute_uri(f.url) if request else f.url
    except Exception:
        return None


def initials(name):
    parts = (name or "").split()
    return "".join(p[0] for p in parts[:2]).upper() or "?"


# ---------------- audience ----------------
def parse_audience(company, d, obj):
    """Validate audience_type / audience_ids from a payload onto obj."""
    if "audience_type" not in d and "audience_ids" not in d:
        return
    at = str(d.get("audience_type", obj.audience_type or "ALL")).upper()
    if at not in ("ALL", "DEPARTMENT", "BRANCH"):
        raise ValueError("audience_type must be ALL, DEPARTMENT or BRANCH.")
    ids = d.get("audience_ids", obj.audience_ids or [])
    if isinstance(ids, str):
        ids = [x for x in ids.replace(" ", "").split(",") if x]
    try:
        ids = sorted({int(i) for i in (ids or [])})
    except (TypeError, ValueError):
        raise ValueError("audience_ids must be a list of ids.")
    if at == "ALL":
        ids = []
    else:
        if not ids:
            raise ValueError(f"audience_ids is required when audience_type is {at}.")
        model = Department if at == "DEPARTMENT" else Branch
        found = set(model.objects.filter(company=company, id__in=ids).values_list("id", flat=True))
        if found != set(ids):
            raise ValueError(f"Unknown {at.lower()} id(s): {sorted(set(ids) - found)}")
    obj.audience_type, obj.audience_ids = at, ids


def audience_info(obj):
    ids = obj.audience_ids or []
    label = "All Organization"
    if obj.audience_type == "DEPARTMENT":
        label = ", ".join(Department.objects.filter(id__in=ids).values_list("name", flat=True)) or "Departments"
    elif obj.audience_type == "BRANCH":
        label = ", ".join(Branch.objects.filter(id__in=ids).values_list("name", flat=True)) or "Branches"
    return {"type": obj.audience_type, "ids": ids, "label": label}


def audience_employees(company, obj):
    qs = employees_qs(company).filter(is_active=True)
    if obj.audience_type == "DEPARTMENT":
        qs = qs.filter(department_id__in=obj.audience_ids or [])
    elif obj.audience_type == "BRANCH":
        qs = qs.filter(people_profile__branch_id__in=obj.audience_ids or [])
    return qs


def visible_to(obj, emp):
    if obj.audience_type == "ALL":
        return True
    ids = set(obj.audience_ids or [])
    if obj.audience_type == "DEPARTMENT":
        return emp.department_id in ids
    prof = getattr(emp, "people_profile", None)
    return bool(prof and prof.branch_id in ids)


# ---------------- announcements ----------------
def live_q(now=None):
    now = now or timezone.now()
    pub = Q(status="PUBLISHED") | Q(status="SCHEDULED", publish_at__lte=now)
    exp = Q(expires_at__isnull=True) | Q(expires_at__gt=now)
    return pub & exp


def effective_status(a, now=None):
    now = now or timezone.now()
    if a.status == "SCHEDULED" and a.publish_at and a.publish_at <= now:
        return "PUBLISHED"
    if a.status == "PUBLISHED" and a.expires_at and a.expires_at <= now:
        return "EXPIRED"
    return a.status


def announcement_metrics(ids):
    """{announcement_id: {views, viewers, reactions{...}, reactions_total, comments}} for a page of ids."""
    m = {i: {"views": 0, "viewers": 0, "reactions": {c: 0 for c, _ in AnnouncementReaction.REACTIONS},
             "reactions_total": 0, "comments": 0} for i in ids}
    for aid, n, v in (AnnouncementView.objects.filter(announcement_id__in=ids, is_active=True)
                      .values_list("announcement_id").annotate(n=Count("id")).annotate(v=Sum("view_count"))):
        m[aid]["viewers"], m[aid]["views"] = n, v or 0
    for aid, r, n in (AnnouncementReaction.objects.filter(announcement_id__in=ids, is_active=True)
                      .values_list("announcement_id", "reaction").annotate(n=Count("id"))):
        m[aid]["reactions"][r] = n
        m[aid]["reactions_total"] += n
    for aid, n in (AnnouncementComment.objects.filter(announcement_id__in=ids, is_active=True)
                   .values_list("announcement_id").annotate(n=Count("id"))):
        m[aid]["comments"] = n
    return m


def announcement_row(a, request, metrics=None, detail=False):
    now = timezone.now()
    author = {"name": a.author_name or (a.author.name if a.author_id else "Company Admin"),
              "title": a.author_title or (a.author.Designation if a.author_id else None),
              "employee_code": a.author.employee_code if a.author_id else None}
    author["initials"] = initials(author["name"])
    row = {"id": a.id, "title": a.title, "body": a.body, "category": a.category,
           "category_label": dict(Announcement.CATEGORY).get(a.category), "priority": a.priority,
           "priority_label": dict(Announcement.PRIORITY).get(a.priority), "status": a.status,
           "effective_status": effective_status(a, now), "publish_at": iso(a.publish_at),
           "published_at": iso(a.published_at), "posted_on": iso(a.published_at or a.publish_at or a.created_at),
           "expires_at": iso(a.expires_at), "is_pinned": a.is_pinned, "allow_comments": a.allow_comments,
           "banner_image": media_url(request, a.banner_image), "audience": audience_info(a), "author": author,
           "created_at": iso(a.created_at), "updated_at": iso(a.updated_at)}
    if metrics is not None:
        row["metrics"] = metrics
    return row


# ---------------- surveys ----------------
def enps_for(survey):
    q = survey.questions.filter(qtype="NPS", is_active=True).order_by("order", "id").first()
    if q is None:
        return None
    ratings = list(SurveyAnswer.objects.filter(question=q, rating__isnull=False).values_list("rating", flat=True))
    n = len(ratings)
    if not n:
        return {"score": None, "responses": 0, "promoters": 0, "passives": 0, "detractors": 0}
    p, d = sum(1 for r in ratings if r >= 9), sum(1 for r in ratings if r <= 6)
    return {"score": round((p - d) * 100 / n), "responses": n, "promoters": p, "passives": n - p - d,
            "detractors": d}


def survey_is_open(s, today=None):
    today = today or timezone.localdate()
    return (s.status == "ACTIVE" and (not s.start_date or s.start_date <= today)
            and (not s.end_date or s.end_date >= today))


def survey_row(s, request=None, responses=None, questions=None):
    rc = responses if responses is not None else s.responses.filter(is_active=True).count()
    qc = questions if questions is not None else s.questions.filter(is_active=True).count()
    rate = round(rc * 100 / s.target_count) if s.target_count else None
    e = enps_for(s) if s.status != "DRAFT" else None
    return {"id": s.id, "title": s.title, "description": s.description, "survey_type": s.survey_type,
            "survey_type_label": dict(Survey.TYPES).get(s.survey_type), "status": s.status,
            "is_open": survey_is_open(s), "is_anonymous": s.is_anonymous,
            "start_date": iso(s.start_date), "end_date": iso(s.end_date), "audience": audience_info(s),
            "question_count": qc, "response_count": rc, "target_count": s.target_count, "response_rate": rate,
            "response_summary": (f"Response Rate: {rate}% ({rc}/{s.target_count} responses received)"
                                 if rate is not None else None),
            "enps": e["score"] if e else None, "launched_at": iso(s.launched_at), "closed_at": iso(s.closed_at),
            "created_at": iso(s.created_at), "updated_at": iso(s.updated_at)}


def question_row(q):
    return {"id": q.id, "survey_id": q.survey_id, "order": q.order, "text": q.text, "qtype": q.qtype,
            "qtype_label": dict(q.QTYPES).get(q.qtype), "options": q.options or [], "is_required": q.is_required}


def clean_question(d):
    from .engagement_models import SurveyQuestion
    text = str(d.get("text") or "").strip()
    if not text:
        raise ValueError("Question text is required.")
    qtype = str(d.get("qtype") or "RATING").upper()
    if qtype not in dict(SurveyQuestion.QTYPES):
        raise ValueError("Invalid qtype. Allowed: " + ", ".join(dict(SurveyQuestion.QTYPES)))
    opts = d.get("options") or []
    if qtype in ("SINGLE", "MULTI"):
        opts = [str(o).strip() for o in opts if str(o).strip()]
        if len(opts) < 2 or len(set(o.lower() for o in opts)) != len(opts):
            raise ValueError("Choice questions need at least 2 unique options.")
    elif qtype == "YES_NO":
        opts = ["Yes", "No"]
    else:
        opts = []
    return {"text": text[:500], "qtype": qtype, "options": opts,
            "is_required": str(d.get("is_required", True)).lower() not in ("false", "0", "no")}


# ---------------- events ----------------
def event_phase(e, now=None):
    now = now or timezone.now()
    if e.is_cancelled:
        return "Cancelled"
    end = e.end_at or (e.start_at + timedelta(hours=2))
    if e.start_at > now:
        return "Upcoming"
    return "Ongoing" if end >= now else "Completed"


def rsvp_counts(ids):
    m = {i: {"going": 0, "maybe": 0, "declined": 0} for i in ids}
    for eid, r, n in (EventRsvp.objects.filter(event_id__in=ids, is_active=True)
                      .values_list("event_id", "response").annotate(n=Count("id"))):
        m[eid][{"GOING": "going", "MAYBE": "maybe", "DECLINED": "declined"}[r]] = n
    return m


def event_row(e, request, counts=None, mine=None):
    start = timezone.localtime(e.start_at)
    row = {"id": e.id, "title": e.title, "event_type": e.event_type,
           "event_type_label": dict(e.TYPES).get(e.event_type), "description": e.description,
           "start_at": iso(e.start_at), "end_at": iso(e.end_at), "date_label": start.strftime("%d %b %Y"),
           "location": e.location, "mode": e.mode, "mode_label": dict(e.MODES).get(e.mode),
           "meeting_link": e.meeting_link, "capacity": e.capacity, "rsvp_required": e.rsvp_required,
           "phase": event_phase(e), "is_cancelled": e.is_cancelled, "cancel_reason": e.cancel_reason,
           "banner_image": media_url(request, e.banner_image), "audience": audience_info(e),
           "created_at": iso(e.created_at), "updated_at": iso(e.updated_at)}
    if counts is not None:
        row["rsvp"] = counts
        row["seats_left"] = None if e.capacity is None else max(e.capacity - counts["going"], 0)
    if mine is not False and mine is not None:
        row["my_rsvp"] = mine
    return row
