# ============================================================
# ADDITIVE: Performance Management & OKRs - shared logic
# ------------------------------------------------------------
# Used by BOTH:
#   Company/performance_api_views.py   (Admin / HR -> /api/performance/...)
#   Employee/performance_self_views.py (Employee    -> /employee/performance/...)
#
# Nothing in the existing hr_api_views.py / leave_engine.py is
# modified; their helpers are imported and reused.
# ============================================================

from datetime import date
from decimal import Decimal, ROUND_HALF_UP

from django.db.models import Avg, Count, Q
from django.utils import timezone

from Company.hr_api_views import (   # existing, unchanged
    _err,
    _ok,
    _truthy,
    employee_brief,
    employee_map,
)
from Company.leave_engine import (   # existing, unchanged
    financial_year,
    fy_range,
    valid_fy,
)
from Employee.models import EmployeeDT
from Employee.leave_models import ReportingHierarchy
from Employee.performance_models import (
    PerfAppraisal,
    PerfGoal,
    PerfImprovementPlan,
    PerfManagerFeedback,
    PerfRatingHistory,
    PerfReviewCycle,
    PerfSelfReview,
)

__all__ = [
    "_err", "_ok", "_truthy", "employee_brief", "employee_map",
    "financial_year", "fy_range", "valid_fy",
]


# ------------------------------------------------------------
# rating bands  (score -> bucket 1..5 -> label)
# ------------------------------------------------------------

RATING_BANDS = [
    # (min score, bucket, label, short label used by the bell curve)
    (Decimal("5.0"), 5, "Outstanding", "Outstanding"),
    (Decimal("4.0"), 4, "Exceeds Expectations", "Exceeds"),
    (Decimal("3.0"), 3, "Meets Expectations", "Meets"),
    (Decimal("2.0"), 2, "Needs Development", "Needs Dev"),
    (Decimal("0.0"), 1, "Unsatisfactory", "Unsatisfactory"),
]

# Reference bell curve (target % per bucket) shown next to the
# actual distribution on the Rating History tab.
REFERENCE_CURVE = {5: 15, 4: 55, 3: 25, 2: 5, 1: 0}

ACTIVE_PIP_STATUSES = ("Active", "Extended")


def _dec(value):
    if value is None or value == "":
        return None
    return Decimal(str(value))


def rating_bucket(score):
    score = _dec(score)
    if score is None:
        return None
    for floor, bucket, _label, _short in RATING_BANDS:
        if score >= floor:
            return bucket
    return 1


def rating_label(score, short=False):
    score = _dec(score)
    if score is None:
        return None
    for floor, _bucket, label, short_label in RATING_BANDS:
        if score >= floor:
            return short_label if short else label
    return RATING_BANDS[-1][3 if short else 2]


def appraisal_label(appraisal):
    """Custom badge text if HR set one, otherwise the band label."""
    return appraisal.rating_label_override or rating_label(appraisal.normalized_rating)


def rating_badge(appraisal):
    """'4.8 - Exceeds Expectations' (dashboard badge)."""
    if appraisal is None or appraisal.normalized_rating is None:
        return None
    return f"{appraisal.normalized_rating} - {appraisal_label(appraisal)}"


def num(value, places=1):
    """Decimal -> float rounded for JSON cards."""
    if value is None:
        return None
    q = Decimal(1).scaleb(-places)
    return float(Decimal(str(value)).quantize(q, rounding=ROUND_HALF_UP))


def fmt_date(d):
    """date(2026, 9, 30) -> '30 September 2026' (as shown in the UI)."""
    return d.strftime("%d %B %Y") if d else None


def fy_label(fy):
    return f"FY {fy}" if fy else None


# ------------------------------------------------------------
# employees / hierarchy
# ------------------------------------------------------------

def employee_mini(emp):
    """Light employee block (no password / bank / statutory data)."""
    if emp is None:
        return None
    department = None
    if getattr(emp, "department_id", None):
        department = getattr(emp.department, "name", None)
    if not department:
        department = getattr(emp, "Department", None)
    return {
        "employee_code": emp.employee_code,
        "name": emp.name,
        "email": emp.email,
        "designation": getattr(emp, "Designation", None),
        "department": department,
    }


def employee_title(emp):
    """'Rahul Sharma (Senior Full Stack Engineer)'"""
    if emp is None:
        return None
    desig = getattr(emp, "Designation", None)
    return f"{emp.name} ({desig})" if desig else emp.name


def get_employee(company, code):
    if not code:
        return None
    return EmployeeDT.objects.filter(company=company, employee_code=code).first()


def manager_code_of(company, employee_code):
    row = ReportingHierarchy.objects.filter(
        company=company, Employee_ID=employee_code, is_active=True
    ).first()
    return row.manager_code if row else None


def direct_report_codes(company, manager_code):
    return list(
        ReportingHierarchy.objects.filter(
            company=company, manager_code=manager_code, is_active=True
        ).values_list("Employee_ID", flat=True)
    )


def eligible_employees(company, cycle):
    """
    Employees eligible for a cycle: active, and joined before
    cycle.eligible_joined_before (when set). Employees without a
    joining date cannot be proven ineligible, so they are included
    and counted separately by the caller.
    """
    qs = EmployeeDT.objects.filter(company=company, is_active=True)
    if cycle.eligible_joined_before:
        qs = qs.filter(
            Q(Date_of_Joining__lt=cycle.eligible_joined_before)
            | Q(Date_of_Joining__isnull=True)
        )
    return qs.select_related("department")


# ------------------------------------------------------------
# cycles
# ------------------------------------------------------------

def cycle_label(cycle):
    return cycle.name if cycle else None


def cycle_period(cycle):
    if cycle is None:
        return None
    return cycle.period_label or cycle.name


def eligibility_text(cycle):
    if cycle.eligible_joined_before:
        return f"All employees joined before {fmt_date(cycle.eligible_joined_before)}"
    return "All employees"


def default_fy_for_cycle(attrs):
    """FY from explicit value, else from deadline / start / today."""
    if attrs.get("financial_year"):
        return attrs["financial_year"]
    d = attrs.get("submission_deadline") or attrs.get("start_date") or timezone.localdate()
    return financial_year(d)


def resolve_scope(company, params):
    """
    Which appraisals / ratings does a dashboard or bell curve cover?
      ?cycle_id=<id>           -> that review cycle
      ?financial_year=2026-27  -> that financial year
      (nothing)                -> the newest ACTIVE cycle, else the current FY
    Returns (cycle_or_None, financial_year_or_None, error_or_None)
    """
    cycle_id = params.get("cycle_id") or params.get("cycle")
    fy = params.get("financial_year")

    if cycle_id:
        try:
            cycle = PerfReviewCycle.objects.filter(company=company, pk=int(cycle_id)).first()
        except (TypeError, ValueError):
            return None, None, "cycle_id must be a number."
        if cycle is None:
            return None, None, "Review cycle not found."
        return cycle, cycle.financial_year or None, None

    if fy:
        if not valid_fy(fy):
            return None, None, "financial_year must look like 2026-27."
        return None, fy, None

    cycle = (
        PerfReviewCycle.objects.filter(company=company, status="Active", is_active=True)
        .order_by("-submission_deadline", "-id").first()
    )
    if cycle:
        return cycle, cycle.financial_year or None, None
    return None, financial_year(), None


def appraisal_scope_qs(company, cycle, fy):
    qs = PerfAppraisal.objects.filter(company=company, is_active=True)
    if cycle is not None:
        return qs.filter(cycle=cycle)
    if fy:
        return qs.filter(Q(financial_year=fy) | Q(cycle__financial_year=fy))
    return qs


def goal_scope_qs(company, cycle, fy):
    qs = PerfGoal.objects.filter(company=company, is_active=True)
    if cycle is not None:
        return qs.filter(cycle=cycle)
    if fy:
        return qs.filter(Q(financial_year=fy) | Q(cycle__financial_year=fy))
    return qs


# ------------------------------------------------------------
# goals
# ------------------------------------------------------------

def calc_progress(current, target):
    current, target = _dec(current), _dec(target)
    if current is None or not target:
        return None
    pct = (current / target * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return max(Decimal("0"), min(Decimal("100"), pct))


def apply_goal_progress(attrs, instance=None):
    """
    Keeps progress / status / completed_at consistent. Mutates `attrs`
    (serializer validated_data) and returns it.

      - progress_percent not sent but current/target are -> calculated
      - status not sent -> Completed at 100%, In Progress above 0%
      - completed_at is set / cleared with the status
    """
    target = attrs.get("target_value", instance.target_value if instance else None)
    current = attrs.get("current_value", instance.current_value if instance else None)

    if "progress_percent" not in attrs and (
        "current_value" in attrs or "target_value" in attrs
    ):
        pct = calc_progress(current, target)
        if pct is not None:
            attrs["progress_percent"] = pct

    progress = _dec(attrs.get("progress_percent", instance.progress_percent if instance else 0)) or Decimal("0")
    old_status = instance.status if instance else "Not Started"

    if "status" not in attrs:
        if progress >= 100:
            attrs["status"] = "Completed"
        elif progress > 0 and old_status == "Not Started":
            attrs["status"] = "In Progress"

    final_status = attrs.get("status", old_status)
    if final_status == "Completed":
        if instance is None or instance.completed_at is None:
            attrs["completed_at"] = timezone.now()
        if "progress_percent" not in attrs and progress < 100 and "status" in attrs:
            attrs["progress_percent"] = Decimal("100")
    else:
        attrs["completed_at"] = None

    return attrs


# ------------------------------------------------------------
# appraisal side effects
# ------------------------------------------------------------

def sync_rating_history(appraisal, actor=None):
    """
    A COMPLETED appraisal with a rating is mirrored into
    PerfRatingHistory (one row per employee per cycle) - this is the
    source of the Rating History tab / bell curve.
    """
    rating = appraisal.normalized_rating
    if appraisal.status != "Completed" or rating is None:
        return None

    cycle = appraisal.cycle
    row, created = PerfRatingHistory.objects.get_or_create(
        company=appraisal.company,
        employee=appraisal.employee,
        cycle=cycle,
        defaults={
            "appraisal": appraisal,
            "period_label": cycle_period(cycle) or "",
            "financial_year": appraisal.financial_year or cycle.financial_year or "",
            "rating": rating,
            "rating_bucket": rating_bucket(rating),
            "rating_label": appraisal_label(appraisal) or "",
            "source": "appraisal",
            "created_by": actor,
            "updated_by": actor,
        },
    )
    if not created:
        row.appraisal = appraisal
        row.rating = rating
        row.rating_bucket = rating_bucket(rating)
        row.rating_label = appraisal_label(appraisal) or ""
        row.period_label = row.period_label or cycle_period(cycle) or ""
        row.financial_year = appraisal.financial_year or cycle.financial_year or row.financial_year
        row.source = "appraisal"
        row.updated_by = actor
        row.id_version = (row.id_version or 1) + 1
        row.save()
    return row


def after_appraisal_save(appraisal, actor=None):
    """Fill FY / completed_at and mirror into rating history."""
    changed = []
    if not appraisal.financial_year and appraisal.cycle.financial_year:
        appraisal.financial_year = appraisal.cycle.financial_year
        changed.append("financial_year")
    if appraisal.status == "Completed" and appraisal.completed_at is None:
        appraisal.completed_at = timezone.now()
        changed.append("completed_at")
    if appraisal.status != "Completed" and appraisal.completed_at is not None:
        appraisal.completed_at = None
        changed.append("completed_at")
    if changed:
        appraisal.save(update_fields=changed + ["updated_at"])
    sync_rating_history(appraisal, actor)
    return appraisal


def after_self_review_save(review, actor=None):
    """
    A SUBMITTED self review stamps submitted_at, links (or creates)
    the appraisal row, copies the self score and moves the appraisal
    from 'Pending Self Review' to 'Pending Manager Review'.
    """
    if review.status != "Submitted":
        if review.submitted_at is not None:
            review.submitted_at = None
            review.save(update_fields=["submitted_at", "updated_at"])
        return review

    if review.submitted_at is None:
        review.submitted_at = timezone.now()

    appraisal = review.appraisal
    if appraisal is None:
        appraisal, _ = PerfAppraisal.objects.get_or_create(
            company=review.company, employee=review.employee, cycle=review.cycle,
            defaults={
                "financial_year": review.cycle.financial_year or "",
                "reviewer_code": manager_code_of(review.company, review.employee.employee_code) or "",
                "created_by": actor, "updated_by": actor,
            },
        )
        review.appraisal = appraisal

    if review.self_score is not None:
        appraisal.self_score = review.self_score
    if appraisal.status == "Pending Self Review":
        appraisal.status = "Pending Manager Review"
    appraisal.updated_by = actor
    appraisal.save()

    review.save(update_fields=["submitted_at", "appraisal", "updated_at"])
    return review


# ------------------------------------------------------------
# dashboard
# ------------------------------------------------------------

def dashboard_cards(company, cycle, fy):
    appraisals = appraisal_scope_qs(company, cycle, fy)

    agg = appraisals.aggregate(
        total=Count("id"),
        completed=Count("id", filter=Q(status="Completed")),
        avg=Avg("normalized_rating"),
        high_potential=Count("id", filter=Q(potential="High")),
    )
    total = agg["total"] or 0
    completed = agg["completed"] or 0
    avg = agg["avg"]
    completion = (Decimal(completed) / Decimal(total) * 100) if total else Decimal("0")

    pips = PerfImprovementPlan.objects.filter(
        company=company, is_active=True, status__in=ACTIVE_PIP_STATUSES
    ).count()

    basis = cycle_period(cycle) or fy_label(fy)

    return {
        "company_average_rating": {
            "title": "Company Average Rating",
            "value": num(avg),
            "out_of": 5.0,
            "label": f"{num(avg):.1f} / 5.0" if avg is not None else "- / 5.0",
            "caption": f"Based on {basis}" if basis else "",
        },
        "appraisal_completion": {
            "title": "Appraisal Completion",
            "value": num(completion),
            "label": f"{num(completion):.1f}%",
            "completed": completed,
            "total": total,
            "caption": "Review cycles submitted",
        },
        "high_potential_talent": {
            "title": "High Potential Talent",
            "value": agg["high_potential"] or 0,
            "label": str(agg["high_potential"] or 0),
            "caption": "9-Box grid top quadrant",
        },
        "performance_pips": {
            "title": "Performance PIPs",
            "value": pips,
            "label": str(pips),
            "caption": "Active coaching track",
        },
    }


def employee_cards(company, cycle, fy, limit=50, employee_codes=None, request=None):
    """
    The employee cards shared by the Performance Dashboard and the
    Goals / KPIs tab: name (designation), rating badge, cycle line and
    the goal progress bars.
    """
    appraisals = list(
        appraisal_scope_qs(company, cycle, fy)
        .select_related("employee", "employee__department", "cycle")
        .order_by("employee__name", "-id")
    )
    goals = list(
        goal_scope_qs(company, cycle, fy)
        .select_related("employee", "employee__department", "cycle")
        .order_by("employee__name", "id")
    )

    if employee_codes is not None:
        codes = set(employee_codes)
        appraisals = [a for a in appraisals if a.employee.employee_code in codes]
        goals = [g for g in goals if g.employee.employee_code in codes]

    cards = {}   # employee pk -> card
    order = []

    def card_for(emp):
        if emp.pk not in cards:
            cards[emp.pk] = {
                "employee": employee_mini(emp),
                "title": employee_title(emp),
                "rating": None,
                "rating_badge": None,
                "appraisal_id": None,
                "appraisal_status": None,
                "cycle_label": None,
                "goals": [],
            }
            order.append(emp.pk)
        return cards[emp.pk]

    for a in appraisals:
        c = card_for(a.employee)
        if c["appraisal_id"] is not None:
            continue   # keep the newest appraisal only
        c["appraisal_id"] = a.pk
        c["appraisal_status"] = a.status
        c["rating"] = num(a.normalized_rating)
        c["rating_badge"] = rating_badge(a)
        c["rating_label"] = appraisal_label(a) if a.normalized_rating is not None else None
        c["cycle_label"] = cycle_label(a.cycle)

    for g in goals:
        c = card_for(g.employee)
        if not c["cycle_label"]:
            c["cycle_label"] = cycle_label(g.cycle) or fy_label(g.financial_year)
        c["goals"].append({
            "id": g.pk,
            "title": g.title,
            "goal_type": g.goal_type,
            "progress_percent": num(g.progress_percent, 0),
            "status": g.status,
            "due_date": g.due_date,
        })

    return [cards[pk] for pk in order[:limit]]


# ------------------------------------------------------------
# bell curve (Rating History)
# ------------------------------------------------------------

def rating_distribution(company, cycle, fy):
    """
    Latest rating per employee inside the scope, grouped into the
    5 / 4 / 3 / 2 / 1 buckets, next to the reference bell curve.
    """
    qs = PerfRatingHistory.objects.filter(company=company, is_active=True)
    if cycle is not None:
        qs = qs.filter(cycle=cycle)
    elif fy:
        qs = qs.filter(Q(financial_year=fy) | Q(cycle__financial_year=fy))

    latest = {}
    for row in qs.order_by("employee_id", "-created_at", "-id"):
        latest.setdefault(row.employee_id, row)

    counts = {b: 0 for b in (5, 4, 3, 2, 1)}
    ratings = []
    for row in latest.values():
        counts[row.rating_bucket] = counts.get(row.rating_bucket, 0) + 1
        ratings.append(row.rating)

    total = sum(counts.values())
    rows = []
    for _floor, bucket, label, short in RATING_BANDS:
        count = counts.get(bucket, 0)
        pct = (Decimal(count) / Decimal(total) * 100) if total else Decimal("0")
        rows.append({
            "rating": bucket,
            "label": label,
            "short_label": short,
            "title": f"Rating {bucket} ({short})",
            "count": count,
            "percent": num(pct),
            "percent_label": f"{num(pct):g}%",
            "reference_percent": REFERENCE_CURVE[bucket],
            "deviation": num(pct - REFERENCE_CURVE[bucket]),
        })

    avg = (sum(ratings) / len(ratings)) if ratings else None
    return {
        "total_rated": total,
        "average_rating": num(avg),
        "distribution": rows,
        "reference_curve": REFERENCE_CURVE,
    }
