"""Operations workload, capacity and KPI calculation service.

This module keeps all workload calculations outside Flask routes.  It preserves
existing workload-entry behaviour and adds read-only aggregation helpers for:

* Workload analytics
* Capacity utilisation
* Operations KPI preview

The service does not modify assignment, QC, billing, PMS or Sales KPI logic.
"""



from collections import defaultdict
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple

from flask import current_app
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import joinedload

from app import db
from app.models import (
    EmployeeProfile,
    OperationsJobcard,
    OperationsJobcardAssignment,
    OperationsJobcardService,
    OperationsJobcardWorkloadEntry,
    OperationsKpiProfile,
    OperationsWorkloadStandard,
    User,
    WorkforceGroup,
)

FOUR_PLACES = Decimal("0.0001")
TWO_PLACES = Decimal("0.01")
ONE_HUNDRED = Decimal("100")
MINUTES_PER_HOUR = Decimal("60")

DEFAULT_MONTHLY_WORKING_DAYS = Decimal("22")
DEFAULT_DAILY_WORKING_HOURS = Decimal("8")
OPERATIONS_WORKFORCE_CODE = "OPERATIONS"

ACTIVE_ASSIGNMENT_STATUSES = {
    "assigned",
    "in progress",
    "on hold",
    "delegated",
}
COMPLETED_ASSIGNMENT_STATUSES = {"completed", "done", "submitted"}
EXCLUDED_ASSIGNMENT_STATUSES = {"cancelled", "replaced", "rejected"}


# ---------------------------------------------------------------------------
# Decimal and date helpers
# ---------------------------------------------------------------------------


def _decimal(value: Any, default: str = "0") -> Decimal:
    try:
        return Decimal(str(value if value not in (None, "") else default))
    except (InvalidOperation, TypeError, ValueError):
        return Decimal(default)


def _quantize(value: Any, places: Decimal = TWO_PLACES) -> Decimal:
    return _decimal(value).quantize(places, rounding=ROUND_HALF_UP)


def _hours(minutes: Any) -> Decimal:
    return (_decimal(minutes) / MINUTES_PER_HOUR).quantize(
        TWO_PLACES,
        rounding=ROUND_HALF_UP,
    )


def _percentage(numerator: Any, denominator: Any) -> Decimal:
    denominator_value = _decimal(denominator)
    if denominator_value <= 0:
        return Decimal("0.00")
    return ((_decimal(numerator) / denominator_value) * ONE_HUNDRED).quantize(
        TWO_PLACES,
        rounding=ROUND_HALF_UP,
    )


def _normalise(value: Any) -> str:
    return str(value or "").strip().lower()


def _workload_service_matches_assignment(assignment, standard_or_entry) -> bool:
    """Return True only when workload classification belongs to the assignment service.

    Workload standards are service-specific.  A Translation assignment must not
    be calculated with (for example) a File Formatting standard simply because
    Application/SOW/Complexity happen to match.
    """
    if not assignment or not assignment.jobcard_service:
        return False

    assignment_service = _normalise(assignment.jobcard_service.service_name)
    workload_service = _normalise(
        getattr(standard_or_entry, "service_name", None)
        or getattr(standard_or_entry, "service_snapshot", None)
    )
    return bool(assignment_service and workload_service and assignment_service == workload_service)


def _start_of_day(value: date) -> datetime:
    return datetime.combine(value, time.min)


def _end_exclusive(value: date) -> datetime:
    return datetime.combine(value + timedelta(days=1), time.min)


def month_bounds(year: int, month: int) -> Tuple[date, date]:
    start = date(year, month, 1)
    if month == 12:
        end = date(year + 1, 1, 1)
    else:
        end = date(year, month + 1, 1)
    return start, end


def resolve_date_range(
    start_date: Optional[date] = None,
    end_date: Optional[date] = None,
    year: Optional[int] = None,
    month: Optional[int] = None,
) -> Tuple[date, date]:
    """Return an inclusive date range.

    If no explicit dates are supplied, the current month is used.
    """
    today = date.today()

    if year and month:
        start, next_month = month_bounds(int(year), int(month))
        return start, next_month - timedelta(days=1)

    if start_date and end_date:
        return start_date, end_date

    start, next_month = month_bounds(today.year, today.month)
    return start, next_month - timedelta(days=1)


# ---------------------------------------------------------------------------
# Existing workload-entry behaviour
# ---------------------------------------------------------------------------


def calculate_minutes(standard, quantity):
    quantity_value = _decimal(quantity)
    base_quantity = _decimal(standard.base_quantity, "1")
    minutes = _decimal(standard.standard_minutes)

    if quantity_value <= 0:
        raise ValueError("Quantity must be greater than zero.")
    if base_quantity <= 0:
        raise ValueError("The workload standard has an invalid base quantity.")
    if minutes < 0:
        raise ValueError("The workload standard has invalid standard minutes.")

    return ((quantity_value / base_quantity) * minutes).quantize(
        FOUR_PLACES,
        rounding=ROUND_HALF_UP,
    )


def create_workload_entry(
    assignment,
    standard,
    quantity,
    user_id,
    source="LIVE_ENTRY",
):
    if not isinstance(assignment, OperationsJobcardAssignment):
        raise ValueError("Invalid assignment.")
    if not isinstance(standard, OperationsWorkloadStandard) or not standard.is_active:
        raise ValueError("Please select an active workload standard.")
    if not assignment_requires_workload(assignment):
        raise ValueError("This assignment is not eligible for workload entry.")
    if not _workload_service_matches_assignment(assignment, standard):
        actual_service = (assignment.jobcard_service.service_name or "this service").strip()
        selected_service = (standard.service_name or "another service").strip()
        raise ValueError(
            f"Workload classification mismatch: {actual_service} assignments can only use "
            f"{actual_service} workload standards (selected: {selected_service})."
        )

    calculated_minutes = calculate_minutes(standard, quantity)

    entry = OperationsJobcardWorkloadEntry(
        assignment_id=assignment.id,
        jobcard_service_id=assignment.jobcard_service_id,
        workload_standard_id=standard.id,
        application_snapshot=standard.application_name,
        file_extension_snapshot=standard.file_extension,
        sow_snapshot=standard.sow,
        service_snapshot=standard.service_name,
        complexity_snapshot=standard.complexity,
        unit_type_snapshot=standard.unit_type,
        base_quantity_snapshot=standard.base_quantity,
        standard_minutes_snapshot=standard.standard_minutes,
        quantity=_decimal(quantity).quantize(FOUR_PLACES, rounding=ROUND_HALF_UP),
        calculated_minutes=calculated_minutes,
        source=source,
        created_by_id=user_id,
        updated_by_id=user_id,
    )
    db.session.add(entry)
    return entry


def deactivate_workload_entry(entry, user_id):
    """Soft-delete an entry without removing its audit history."""
    if not isinstance(entry, OperationsJobcardWorkloadEntry):
        raise ValueError("Invalid workload entry.")

    entry.is_active = False
    entry.updated_by_id = user_id
    entry.updated_at = datetime.utcnow()
    return entry


def assignment_requires_workload(assignment):
    if not assignment:
        return False

    if _normalise(assignment.assignment_type).upper() not in {"PRODUCTION", "QC"}:
        return False

    if _normalise(assignment.status) in EXCLUDED_ASSIGNMENT_STATUSES:
        return False

    if assignment.replaced_at is not None:
        return False

    # Fully delegated parents are not credited separately. Their child rows are
    # validated and reported, preventing double counting.
    try:
        has_children = assignment.child_assignments.count() > 0
    except Exception:
        has_children = False

    if _normalise(assignment.status) == "delegated" and has_children:
        return False

    return str(assignment.assigned_to_type or "").upper() == "INTERNAL"


def required_assignments_for_jobcard(jobcard):
    rows = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id
            == OperationsJobcardAssignment.jobcard_service_id,
        )
        .filter(OperationsJobcardService.jobcard_id == jobcard.id)
        .order_by(OperationsJobcardAssignment.id.asc())
        .all()
    )
    return [row for row in rows if assignment_requires_workload(row)]


def missing_workload_assignments(jobcard):
    required = required_assignments_for_jobcard(jobcard)
    if not required:
        return []

    assignment_ids = [row.id for row in required]
    active_entries = (
        OperationsJobcardWorkloadEntry.query
        .filter(
            OperationsJobcardWorkloadEntry.assignment_id.in_(assignment_ids),
            OperationsJobcardWorkloadEntry.is_active.is_(True),
        )
        .options(
            joinedload(OperationsJobcardWorkloadEntry.assignment)
            .joinedload(OperationsJobcardAssignment.jobcard_service)
        )
        .all()
    )
    completed_ids = {
        entry.assignment_id
        for entry in active_entries
        if _workload_service_matches_assignment(entry.assignment, entry)
    }
    return [row for row in required if row.id not in completed_ids]


def workload_completion_summary(jobcard):
    required = required_assignments_for_jobcard(jobcard)
    missing = missing_workload_assignments(jobcard)
    completed_count = max(len(required) - len(missing), 0)
    return {
        "required_count": len(required),
        "completed_count": completed_count,
        "missing_count": len(missing),
        "is_complete": len(missing) == 0,
        "missing_assignments": missing,
    }


def assignment_display_name(assignment):
    service_name = (
        assignment.jobcard_service.service_name
        if assignment.jobcard_service
        else "Service"
    )
    if assignment.vendor:
        assignee = assignment.vendor.name
    elif assignment.internal_user:
        assignee = assignment.internal_user.name
    else:
        assignee = "Unassigned"
    return f"{service_name} - {assignment.assignment_type.title()} - {assignee}"


# ---------------------------------------------------------------------------
# Common analytics scope
# ---------------------------------------------------------------------------


def team_user_ids(manager_user_id: int, include_self: bool = True) -> List[int]:
    """Return manager + recursive reportees using EmployeeProfile."""
    seen = {manager_user_id} if include_self else set()
    stack = [manager_user_id]

    while stack:
        manager_id = stack.pop()
        rows = (
            EmployeeProfile.query
            .filter(EmployeeProfile.reporting_manager_user_id == manager_id)
            .with_entities(EmployeeProfile.user_id)
            .all()
        )
        for (user_id,) in rows:
            if user_id and user_id not in seen:
                seen.add(user_id)
                stack.append(user_id)

    return sorted(seen)


def direct_reportee_user_ids(manager_user_id: int) -> List[int]:
    """Return active direct reportee user IDs for a manager."""
    rows = (
        EmployeeProfile.query
        .join(User, User.id == EmployeeProfile.user_id)
        .filter(EmployeeProfile.reporting_manager_user_id == manager_user_id)
        .filter(User.is_active.is_(True))
        .with_entities(EmployeeProfile.user_id)
        .all()
    )
    return sorted({user_id for (user_id,) in rows if user_id})


def _manager_team_user_ids(
    manager_user_id: int,
    include_indirect: Optional[bool] = None,
) -> List[int]:
    """Return reportees used for a manager's team KPI."""
    if include_indirect is None:
        include_indirect = bool(
            current_app.config.get(
                "OPERATIONS_MANAGER_INCLUDE_INDIRECT_REPORTEES",
                True,
            )
        )
    if include_indirect:
        return team_user_ids(manager_user_id, include_self=False)
    return direct_reportee_user_ids(manager_user_id)


def _manager_kpi_weights() -> Dict[str, Decimal]:
    """Return normalised manager individual/team KPI weights."""
    individual = _decimal(
        current_app.config.get(
            "OPERATIONS_MANAGER_INDIVIDUAL_KPI_WEIGHT",
            40,
        )
    )
    team = _decimal(
        current_app.config.get(
            "OPERATIONS_MANAGER_TEAM_KPI_WEIGHT",
            60,
        )
    )

    individual = max(individual, Decimal("0"))
    team = max(team, Decimal("0"))
    total = individual + team
    if total <= 0:
        individual = Decimal("40")
        team = Decimal("60")
        total = Decimal("100")

    return {
        "individual": _quantize(individual * ONE_HUNDRED / total, TWO_PLACES),
        "team": _quantize(team * ONE_HUNDRED / total, TWO_PLACES),
    }


def _assignment_is_completed(assignment) -> bool:
    if assignment.completed_at:
        return True
    return _normalise(assignment.status) in COMPLETED_ASSIGNMENT_STATUSES


def _assignment_is_overdue(assignment, now: Optional[datetime] = None) -> bool:
    if _assignment_is_completed(assignment):
        return False
    if not assignment.deadline:
        return False
    return assignment.deadline < (now or datetime.utcnow())


def _assignment_completed_on_time(assignment) -> bool:
    if not _assignment_is_completed(assignment):
        return False
    if not assignment.deadline:
        return True
    completed_at = assignment.completed_at or datetime.utcnow()
    return completed_at <= assignment.deadline


def _entry_scope_query(
    start_date: date,
    end_date: date,
    user_ids: Optional[Sequence[int]] = None,
    department: Optional[str] = None,
    service_name: Optional[str] = None,
    assignment_type: Optional[str] = None,
    assigned_to_type: Optional[str] = None,
    include_vendors: bool = True,
):
    """Build the common workload analytics query.

    Date scope is based on assignment assigned_at.  This keeps assigned,
    completed, pending and overdue values within one consistent cohort.
    """
    query = (
        OperationsJobcardWorkloadEntry.query
        .join(
            OperationsJobcardAssignment,
            OperationsJobcardAssignment.id
            == OperationsJobcardWorkloadEntry.assignment_id,
        )
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id
            == OperationsJobcardWorkloadEntry.jobcard_service_id,
        )
        .join(
            OperationsJobcard,
            OperationsJobcard.id == OperationsJobcardService.jobcard_id,
        )
        .options(
            joinedload(OperationsJobcardWorkloadEntry.assignment)
            .joinedload(OperationsJobcardAssignment.internal_user),
            joinedload(OperationsJobcardWorkloadEntry.assignment)
            .joinedload(OperationsJobcardAssignment.vendor),
            joinedload(OperationsJobcardWorkloadEntry.jobcard_service)
            .joinedload(OperationsJobcardService.jobcard),
        )
        .filter(OperationsJobcardWorkloadEntry.is_active.is_(True))
        # Historical rows created with a workload standard belonging to a
        # different service are invalid and must not inflate KPI/workload.
        .filter(
            func.lower(func.trim(func.coalesce(OperationsJobcardWorkloadEntry.service_snapshot, "")))
            == func.lower(func.trim(func.coalesce(OperationsJobcardService.service_name, "")))
        )
        .filter(OperationsJobcardAssignment.replaced_at.is_(None))
        .filter(
            func.lower(func.coalesce(OperationsJobcardAssignment.status, ""))
            .notin_(EXCLUDED_ASSIGNMENT_STATUSES)
        )
        .filter(OperationsJobcardAssignment.assigned_at >= _start_of_day(start_date))
        .filter(OperationsJobcardAssignment.assigned_at < _end_exclusive(end_date))
    )

    if user_ids:
        query = query.filter(
            OperationsJobcardAssignment.internal_user_id.in_(list(user_ids))
        )

    if not include_vendors:
        query = query.filter(
            OperationsJobcardAssignment.assigned_to_type == "INTERNAL"
        )

    if service_name:
        query = query.filter(
            func.lower(func.trim(OperationsJobcardService.service_name))
            == _normalise(service_name)
        )

    if assignment_type:
        query = query.filter(
            OperationsJobcardAssignment.assignment_type
            == str(assignment_type).upper()
        )

    if assigned_to_type:
        query = query.filter(
            OperationsJobcardAssignment.assigned_to_type
            == str(assigned_to_type).upper()
        )

    if department:
        query = (
            query
            .join(
                User,
                User.id == OperationsJobcardAssignment.internal_user_id,
            )
            .join(EmployeeProfile, EmployeeProfile.user_id == User.id)
            .filter(EmployeeProfile.department == department)
        )

    return query


def workload_entries_for_period(
    start_date: date,
    end_date: date,
    **filters,
) -> List[OperationsJobcardWorkloadEntry]:
    return _entry_scope_query(start_date, end_date, **filters).all()


# ---------------------------------------------------------------------------
# Workload analytics dashboard
# ---------------------------------------------------------------------------


def _empty_breakdown_row(label: str) -> Dict[str, Any]:
    return {
        "label": label or "Unspecified",
        "minutes": Decimal("0"),
        "hours": Decimal("0"),
        "entries": 0,
    }


def _finalise_breakdown(mapping: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]:
    rows = []
    for row in mapping.values():
        row["minutes"] = _quantize(row["minutes"], FOUR_PLACES)
        row["hours"] = _hours(row["minutes"])
        rows.append(row)
    return sorted(rows, key=lambda item: item["minutes"], reverse=True)


def build_workload_dashboard(
    start_date: Optional[date] = None,
    end_date: Optional[date] = None,
    user_ids: Optional[Sequence[int]] = None,
    department: Optional[str] = None,
    service_name: Optional[str] = None,
    assignment_type: Optional[str] = None,
    assigned_to_type: Optional[str] = None,
) -> Dict[str, Any]:
    start_date, end_date = resolve_date_range(start_date, end_date)
    entries = workload_entries_for_period(
        start_date,
        end_date,
        user_ids=user_ids,
        department=department,
        service_name=service_name,
        assignment_type=assignment_type,
        assigned_to_type=assigned_to_type,
        include_vendors=True,
    )

    total_minutes = Decimal("0")
    completed_minutes = Decimal("0")
    active_minutes = Decimal("0")
    overdue_minutes = Decimal("0")
    production_minutes = Decimal("0")
    qc_minutes = Decimal("0")
    internal_minutes = Decimal("0")
    vendor_minutes = Decimal("0")

    by_employee = {}
    by_vendor = {}
    employee_details = defaultdict(lambda: defaultdict(list))
    vendor_details = defaultdict(lambda: defaultdict(list))
    by_service = {}
    by_application = {}
    by_sow = {}
    by_complexity = {}
    by_client = {}
    by_jobcard = {}
    by_month = {}

    seen_assignments = set()
    completed_assignment_ids = set()
    overdue_assignment_ids = set()

    for entry in entries:
        assignment = entry.assignment
        service = entry.jobcard_service
        jobcard = service.jobcard if service else None
        minutes = _decimal(entry.calculated_minutes)
        total_minutes += minutes

        is_completed = _assignment_is_completed(assignment)
        is_overdue = _assignment_is_overdue(assignment)

        if is_completed:
            completed_minutes += minutes
            completed_assignment_ids.add(assignment.id)
        else:
            active_minutes += minutes

        if is_overdue:
            overdue_minutes += minutes
            overdue_assignment_ids.add(assignment.id)

        assignment_kind = str(assignment.assignment_type or "").upper()
        if assignment_kind == "QC":
            qc_minutes += minutes
        else:
            production_minutes += minutes

        assignee_type = str(assignment.assigned_to_type or "").upper()
        if assignee_type == "INTERNAL":
            internal_minutes += minutes
            user = assignment.internal_user
            label = user.name if user else "Unassigned Internal"
            key = str(user.id if user else "unassigned")
            row = by_employee.setdefault(key, {
                "id": user.id if user else None,
                "label": label,
                "email": user.email if user else None,
                "minutes": Decimal("0"),
                "completed_minutes": Decimal("0"),
                "active_minutes": Decimal("0"),
                "overdue_minutes": Decimal("0"),
                "entries": 0,
                "assignments": set(),
            })
        else:
            vendor_minutes += minutes
            vendor = assignment.vendor
            label = vendor.name if vendor else "Unassigned Vendor"
            key = str(vendor.id if vendor else "unassigned")
            row = by_vendor.setdefault(key, {
                "id": vendor.id if vendor else None,
                "label": label,
                "email": vendor.email if vendor else None,
                "minutes": Decimal("0"),
                "completed_minutes": Decimal("0"),
                "active_minutes": Decimal("0"),
                "overdue_minutes": Decimal("0"),
                "entries": 0,
                "assignments": set(),
            })

        row["minutes"] += minutes
        row["entries"] += 1
        row["assignments"].add(assignment.id)

        detail_map = employee_details if assignee_type == "INTERNAL" else vendor_details
        detail_key = str(
            assignment.internal_user_id
            if assignee_type == "INTERNAL"
            else assignment.vendor_id
            or "unassigned"
        )
        detail_map[detail_key][str(jobcard.id if jobcard else "unknown")].append({
            "entry_id": entry.id,
            "assignment_id": assignment.id,
            "assignment_type": assignment_kind or "PRODUCTION",
            "assignment_status": assignment.status or "Assigned",
            "assigned_at": assignment.assigned_at,
            "deadline": assignment.deadline,
            "completed_at": assignment.completed_at,
            "is_completed": is_completed,
            "is_overdue": is_overdue,
            "service": service.service_name if service and service.service_name else "Unspecified",
            "workload_master_service": entry.service_snapshot or "Unspecified",
            "application": entry.application_snapshot or "Unspecified",
            "file_extension": entry.file_extension_snapshot or "-",
            "sow": entry.sow_snapshot or "Unspecified",
            "complexity": entry.complexity_snapshot or "Unspecified",
            "unit_type": entry.unit_type_snapshot or "Quantity",
            "base_quantity": _quantize(entry.base_quantity_snapshot, FOUR_PLACES),
            "standard_minutes": _quantize(entry.standard_minutes_snapshot, FOUR_PLACES),
            "quantity": _quantize(entry.quantity, FOUR_PLACES),
            "calculated_minutes": _quantize(entry.calculated_minutes, FOUR_PLACES),
            "calculated_hours": _hours(entry.calculated_minutes),
            "calculation_rule": "({0} / {1}) x {2} = {3} minutes".format(
                _quantize(entry.quantity, FOUR_PLACES),
                _quantize(entry.base_quantity_snapshot, FOUR_PLACES),
                _quantize(entry.standard_minutes_snapshot, FOUR_PLACES),
                _quantize(entry.calculated_minutes, FOUR_PLACES),
            ),
            "source": entry.source or "LIVE_ENTRY",
        })
        if is_completed:
            row["completed_minutes"] += minutes
        else:
            row["active_minutes"] += minutes
        if is_overdue:
            row["overdue_minutes"] += minutes

        breakdown_values = (
            (by_service, service.service_name if service else None),
            (by_application, entry.application_snapshot),
            (by_sow, entry.sow_snapshot),
            (by_complexity, entry.complexity_snapshot),
        )
        for mapping, label in breakdown_values:
            label = label or "Unspecified"
            breakdown = mapping.setdefault(label, _empty_breakdown_row(label))
            breakdown["minutes"] += minutes
            breakdown["entries"] += 1

        client_label = "Unspecified Client"
        if jobcard and jobcard.client:
            client_label = jobcard.client.company_name or client_label
        client_row = by_client.setdefault(
            client_label,
            _empty_breakdown_row(client_label),
        )
        client_row["minutes"] += minutes
        client_row["entries"] += 1

        jobcard_key = str(jobcard.id if jobcard else "unknown")
        jobcard_label = jobcard.jobcard_code if jobcard else "Unknown Jobcard"
        jc_row = by_jobcard.setdefault(jobcard_key, {
            "id": jobcard.id if jobcard else None,
            "label": jobcard_label,
            "client": client_label,
            "status": jobcard.status if jobcard else None,
            "minutes": Decimal("0"),
            "completed_minutes": Decimal("0"),
            "active_minutes": Decimal("0"),
            "overdue_minutes": Decimal("0"),
            "entries": 0,
        })
        jc_row["minutes"] += minutes
        jc_row["entries"] += 1
        if is_completed:
            jc_row["completed_minutes"] += minutes
        else:
            jc_row["active_minutes"] += minutes
        if is_overdue:
            jc_row["overdue_minutes"] += minutes

        assigned_at = assignment.assigned_at or entry.created_at
        month_key = assigned_at.strftime("%Y-%m") if assigned_at else "Unknown"
        month_label = assigned_at.strftime("%b %Y") if assigned_at else "Unknown"
        month_row = by_month.setdefault(month_key, {
            "key": month_key,
            "label": month_label,
            "minutes": Decimal("0"),
            "completed_minutes": Decimal("0"),
        })
        month_row["minutes"] += minutes
        if is_completed:
            month_row["completed_minutes"] += minutes

        seen_assignments.add(assignment.id)

    def finalise_assignee_rows(mapping, details_mapping):
        rows = []
        for key, row in mapping.items():
            row["hours"] = _hours(row["minutes"])
            row["completed_hours"] = _hours(row["completed_minutes"])
            row["active_hours"] = _hours(row["active_minutes"])
            row["overdue_hours"] = _hours(row["overdue_minutes"])
            row["assignment_count"] = len(row.pop("assignments"))
            row["completion_pct"] = _percentage(
                row["completed_minutes"],
                row["minutes"],
            )
            jobcard_details = []
            for jc_key, detail_rows in details_mapping.get(key, {}).items():
                first_detail = detail_rows[0] if detail_rows else {}
                jc = None
                if jc_key != "unknown":
                    try:
                        jc = OperationsJobcard.query.get(int(jc_key))
                    except (TypeError, ValueError):
                        jc = None
                total_detail_minutes = sum(
                    (_decimal(item.get("calculated_minutes")) for item in detail_rows),
                    Decimal("0"),
                )
                completed_detail_minutes = sum(
                    (
                        _decimal(item.get("calculated_minutes"))
                        for item in detail_rows
                        if item.get("is_completed")
                    ),
                    Decimal("0"),
                )
                jobcard_details.append({
                    "id": jc.id if jc else None,
                    "code": jc.jobcard_code if jc else "Unknown Jobcard",
                    "client": (jc.client.company_name if jc and jc.client else "Unspecified Client"),
                    "status": jc.status if jc else None,
                    "total_hours": _hours(total_detail_minutes),
                    "completed_hours": _hours(completed_detail_minutes),
                    "active_hours": _hours(max(total_detail_minutes - completed_detail_minutes, Decimal("0"))),
                    "entries": len(detail_rows),
                    "assignments": len({item.get("assignment_id") for item in detail_rows}),
                    "details": detail_rows,
                })
            jobcard_details.sort(key=lambda item: _decimal(item["total_hours"]), reverse=True)
            row["jobcard_details"] = jobcard_details
            row["jobcard_count"] = len(jobcard_details)
            rows.append(row)
        return sorted(rows, key=lambda item: item["minutes"], reverse=True)

    jobcard_rows = []
    for row in by_jobcard.values():
        row["hours"] = _hours(row["minutes"])
        row["completed_hours"] = _hours(row["completed_minutes"])
        row["active_hours"] = _hours(row["active_minutes"])
        row["overdue_hours"] = _hours(row["overdue_minutes"])
        jobcard_rows.append(row)
    jobcard_rows.sort(key=lambda item: item["minutes"], reverse=True)

    month_rows = []
    for key in sorted(by_month.keys()):
        row = by_month[key]
        row["hours"] = _hours(row["minutes"])
        row["completed_hours"] = _hours(row["completed_minutes"])
        month_rows.append(row)

    return {
        "period": {
            "start_date": start_date,
            "end_date": end_date,
        },
        "totals": {
            "entries": len(entries),
            "assignments": len(seen_assignments),
            "completed_assignments": len(completed_assignment_ids),
            "overdue_assignments": len(overdue_assignment_ids),
            "total_minutes": _quantize(total_minutes, FOUR_PLACES),
            "total_hours": _hours(total_minutes),
            "completed_hours": _hours(completed_minutes),
            "active_hours": _hours(active_minutes),
            "overdue_hours": _hours(overdue_minutes),
            "production_hours": _hours(production_minutes),
            "qc_hours": _hours(qc_minutes),
            "internal_hours": _hours(internal_minutes),
            "vendor_hours": _hours(vendor_minutes),
            "completion_pct": _percentage(completed_minutes, total_minutes),
        },
        "employees": finalise_assignee_rows(by_employee, employee_details),
        "vendors": finalise_assignee_rows(by_vendor, vendor_details),
        "by_service": _finalise_breakdown(by_service),
        "by_application": _finalise_breakdown(by_application),
        "by_sow": _finalise_breakdown(by_sow),
        "by_complexity": _finalise_breakdown(by_complexity),
        "by_client": _finalise_breakdown(by_client),
        "jobcards": jobcard_rows,
        "monthly_trend": month_rows,
    }


# ---------------------------------------------------------------------------
# Capacity dashboard
# ---------------------------------------------------------------------------


def _working_days_in_period(start_date: date, end_date: date) -> int:
    count = 0
    cursor = start_date
    while cursor <= end_date:
        if cursor.weekday() < 5:
            count += 1
        cursor += timedelta(days=1)
    return count


def default_capacity_minutes(start_date: date, end_date: date) -> Decimal:
    """Calculate capacity from weekdays and configured daily hours.

    Config keys:
      OPERATIONS_DAILY_WORKING_HOURS (default 8)
      OPERATIONS_MONTHLY_WORKING_DAYS (used only as a fallback)
    """
    daily_hours = _decimal(
        current_app.config.get(
            "OPERATIONS_DAILY_WORKING_HOURS",
            DEFAULT_DAILY_WORKING_HOURS,
        ),
        str(DEFAULT_DAILY_WORKING_HOURS),
    )
    working_days = _working_days_in_period(start_date, end_date)

    if working_days <= 0:
        working_days = int(
            _decimal(
                current_app.config.get(
                    "OPERATIONS_MONTHLY_WORKING_DAYS",
                    DEFAULT_MONTHLY_WORKING_DAYS,
                ),
                str(DEFAULT_MONTHLY_WORKING_DAYS),
            )
        )

    return Decimal(working_days) * daily_hours * MINUTES_PER_HOUR


def _operations_user_query():
    """Base query for active users explicitly assigned to Operations."""
    return (
        User.query
        .join(WorkforceGroup, WorkforceGroup.id == User.workforce_group_id)
        .filter(
            User.is_active.is_(True),
            WorkforceGroup.is_active.is_(True),
            func.upper(WorkforceGroup.code) == OPERATIONS_WORKFORCE_CODE,
        )
    )


def _operations_users(user_ids: Optional[Sequence[int]] = None) -> List[User]:
    query = _operations_user_query()
    if user_ids:
        query = query.filter(User.id.in_(list(user_ids)))
    return query.order_by(User.name.asc()).all()


def capacity_status(utilisation_pct: Decimal) -> str:
    if utilisation_pct >= Decimal("110"):
        return "Critical"
    if utilisation_pct >= Decimal("90"):
        return "Heavy"
    if utilisation_pct >= Decimal("70"):
        return "Moderate"
    if utilisation_pct > Decimal("0"):
        return "Light"
    return "Available"


def build_capacity_dashboard(
    start_date: Optional[date] = None,
    end_date: Optional[date] = None,
    user_ids: Optional[Sequence[int]] = None,
    department: Optional[str] = None,
    capacity_overrides: Optional[Dict[int, Any]] = None,
) -> Dict[str, Any]:
    """Build internal-user capacity using workload minutes.

    ``capacity_overrides`` maps user_id to minutes for the selected period.  It
    allows routes to introduce an employee/month capacity table later without
    changing this service contract.
    """
    start_date, end_date = resolve_date_range(start_date, end_date)
    workload = build_workload_dashboard(
        start_date=start_date,
        end_date=end_date,
        user_ids=user_ids,
        department=department,
        assigned_to_type="INTERNAL",
    )

    employee_workload = {
        row["id"]: row
        for row in workload["employees"]
        if row.get("id") is not None
    }

    users_query = _operations_user_query()
    if user_ids:
        users_query = users_query.filter(User.id.in_(list(user_ids)))
    if department:
        users_query = (
            users_query
            .join(EmployeeProfile, EmployeeProfile.user_id == User.id)
            .filter(EmployeeProfile.department == department)
        )
    users = users_query.order_by(User.name.asc()).all()

    default_minutes = default_capacity_minutes(start_date, end_date)
    overrides = capacity_overrides or {}
    rows = []

    total_capacity = Decimal("0")
    total_assigned = Decimal("0")
    total_completed = Decimal("0")
    total_active = Decimal("0")

    for user in users:
        workload_row = employee_workload.get(user.id, {})
        capacity_minutes = _decimal(overrides.get(user.id, default_minutes))
        assigned_minutes = _decimal(workload_row.get("minutes"))
        completed_minutes = _decimal(workload_row.get("completed_minutes"))
        active_minutes = _decimal(workload_row.get("active_minutes"))
        remaining_minutes = capacity_minutes - assigned_minutes
        utilisation = _percentage(assigned_minutes, capacity_minutes)

        profile = getattr(user, "profile", None)
        row = {
            "user": user,
            "user_id": user.id,
            "name": user.name,
            "email": user.email,
            "department": getattr(profile, "department", None) if profile else None,
            "capacity_minutes": _quantize(capacity_minutes, FOUR_PLACES),
            "capacity_hours": _hours(capacity_minutes),
            "assigned_minutes": _quantize(assigned_minutes, FOUR_PLACES),
            "assigned_hours": _hours(assigned_minutes),
            "completed_hours": _hours(completed_minutes),
            "active_hours": _hours(active_minutes),
            "remaining_hours": _hours(max(remaining_minutes, Decimal("0"))),
            "over_capacity_hours": _hours(abs(min(remaining_minutes, Decimal("0")))),
            "utilisation_pct": utilisation,
            "status": capacity_status(utilisation),
            "assignment_count": workload_row.get("assignment_count", 0),
        }
        rows.append(row)

        total_capacity += capacity_minutes
        total_assigned += assigned_minutes
        total_completed += completed_minutes
        total_active += active_minutes

    rows.sort(key=lambda item: item["utilisation_pct"], reverse=True)

    return {
        "period": workload["period"],
        "totals": {
            "users": len(rows),
            "capacity_hours": _hours(total_capacity),
            "assigned_hours": _hours(total_assigned),
            "completed_hours": _hours(total_completed),
            "active_hours": _hours(total_active),
            "remaining_hours": _hours(max(total_capacity - total_assigned, Decimal("0"))),
            "over_capacity_hours": _hours(abs(min(total_capacity - total_assigned, Decimal("0")))),
            "utilisation_pct": _percentage(total_assigned, total_capacity),
            "available_users": sum(1 for row in rows if row["status"] == "Available"),
            "critical_users": sum(1 for row in rows if row["status"] == "Critical"),
        },
        "rows": rows,
    }


# ---------------------------------------------------------------------------
# Operations KPI preview
# ---------------------------------------------------------------------------


DEFAULT_KPI_WEIGHTS = {
    "workload_achievement": Decimal("40"),
    "on_time_completion": Decimal("25"),
    "capacity_utilisation": Decimal("20"),
    "rework_control": Decimal("10"),
    "qc_compliance": Decimal("5"),
}


def normalise_kpi_weights(weights: Optional[Dict[str, Any]] = None) -> Dict[str, Decimal]:
    selected = DEFAULT_KPI_WEIGHTS.copy()
    for key, value in (weights or {}).items():
        if key in selected:
            selected[key] = max(_decimal(value), Decimal("0"))

    total = sum(selected.values(), Decimal("0"))
    if total <= 0:
        return DEFAULT_KPI_WEIGHTS.copy()

    if total != ONE_HUNDRED:
        selected = {
            key: ((value / total) * ONE_HUNDRED).quantize(
                TWO_PLACES,
                rounding=ROUND_HALF_UP,
            )
            for key, value in selected.items()
        }
    return selected


def _score_utilisation(utilisation_pct: Decimal) -> Decimal:
    """Score capacity utilisation without rewarding extreme overload.

    85-100% is treated as full score. Below 85% scales proportionally. Above
    100% reduces gradually to discourage sustained overload.
    """
    utilisation = _decimal(utilisation_pct)
    if utilisation <= 0:
        return Decimal("0.00")
    if utilisation < Decimal("85"):
        return min((utilisation / Decimal("85")) * ONE_HUNDRED, ONE_HUNDRED)
    if utilisation <= Decimal("100"):
        return ONE_HUNDRED

    penalty = (utilisation - Decimal("100")) * Decimal("2")
    return max(ONE_HUNDRED - penalty, Decimal("0"))


def _assignment_metrics_for_user(
    entries: Iterable[OperationsJobcardWorkloadEntry],
    user_id: int,
) -> Dict[str, Any]:
    assignment_map = {}
    total_minutes = Decimal("0")
    completed_minutes = Decimal("0")
    completed_assignments = 0
    on_time_assignments = 0
    rework_minutes = Decimal("0")
    qc_total = 0
    qc_compliant = 0

    for entry in entries:
        assignment = entry.assignment
        if assignment.internal_user_id != user_id:
            continue

        minutes = _decimal(entry.calculated_minutes)
        total_minutes += minutes
        assignment_map[assignment.id] = assignment

        if _assignment_is_completed(assignment):
            completed_minutes += minutes

        if bool(getattr(assignment, "is_rework_assignment", False)):
            rework_minutes += minutes

    for assignment in assignment_map.values():
        if _assignment_is_completed(assignment):
            completed_assignments += 1
            if _assignment_completed_on_time(assignment):
                on_time_assignments += 1

        if str(assignment.assignment_type or "").upper() == "QC":
            qc_total += 1
            checklist_status = _normalise(
                getattr(assignment, "checklist_status", None)
            )
            if checklist_status in {"submitted", "completed"}:
                qc_compliant += 1

    return {
        "total_minutes": total_minutes,
        "completed_minutes": completed_minutes,
        "completed_assignments": completed_assignments,
        "on_time_assignments": on_time_assignments,
        "rework_minutes": rework_minutes,
        "qc_total": qc_total,
        "qc_compliant": qc_compliant,
        "assignment_count": len(assignment_map),
    }


def _profile_weight_dict(profile: Optional[OperationsKpiProfile]) -> Dict[str, Decimal]:
    if not profile:
        return normalise_kpi_weights()
    return normalise_kpi_weights({
        "workload_achievement": profile.workload_achievement_weight,
        "on_time_completion": profile.on_time_completion_weight,
        "capacity_utilisation": profile.capacity_utilisation_weight,
        "rework_control": profile.rework_control_weight,
        "qc_compliance": profile.qc_compliance_weight,
    })


def _normalised_manager_weights(
    individual_value: Any,
    team_value: Any,
) -> Dict[str, Decimal]:
    individual = max(_decimal(individual_value), Decimal("0"))
    team = max(_decimal(team_value), Decimal("0"))
    total = individual + team
    if total <= 0:
        return {"individual": Decimal("40.00"), "team": Decimal("60.00")}
    return {
        "individual": _quantize(individual * ONE_HUNDRED / total, TWO_PLACES),
        "team": _quantize(team * ONE_HUNDRED / total, TWO_PLACES),
    }


def _operations_kpi_profile_for_user(user: User) -> Dict[str, Any]:
    designation_id = (
        user.profile.designation_id
        if getattr(user, "profile", None)
        else None
    )
    profile = (
        OperationsKpiProfile.query
        .filter_by(user_id=user.id, is_active=True)
        .first()
    )
    if profile is None and designation_id:
        profile = (
            OperationsKpiProfile.query
            .filter_by(designation_id=designation_id, user_id=None, is_active=True)
            .first()
        )
    if profile is None:
        profile = (
            OperationsKpiProfile.query
            .filter_by(
                is_default=True,
                designation_id=None,
                user_id=None,
                is_active=True,
            )
            .order_by(OperationsKpiProfile.id.asc())
            .first()
        )

    if profile:
        manager_weights = _normalised_manager_weights(
            profile.manager_individual_weight,
            profile.manager_team_weight,
        )
        include_indirect = bool(profile.include_indirect_reportees)
        profile_name = profile.profile_name
        profile_id = profile.id
    else:
        manager_weights = _manager_kpi_weights()
        include_indirect = bool(
            current_app.config.get(
                "OPERATIONS_MANAGER_INCLUDE_INDIRECT_REPORTEES",
                True,
            )
        )
        profile_name = "System Default"
        profile_id = None

    return {
        "id": profile_id,
        "name": profile_name,
        "weights": _profile_weight_dict(profile),
        "manager_weights": manager_weights,
        "include_indirect_reportees": include_indirect,
    }


def build_operations_kpi_dashboard(
    start_date: Optional[date] = None,
    end_date: Optional[date] = None,
    user_ids: Optional[Sequence[int]] = None,
    department: Optional[str] = None,
    weights: Optional[Dict[str, Any]] = None,
    capacity_overrides: Optional[Dict[int, Any]] = None,
) -> Dict[str, Any]:
    """Build Operations KPI with manager scores linked to team performance.

    Every employee first receives an independent individual KPI. A manager's
    team KPI is a workload-weighted average of the individual KPI scores of
    their direct/recursive reportees. The final manager KPI combines the
    manager's own score and team score using configurable weights.
    """
    start_date, end_date = resolve_date_range(start_date, end_date)
    explicit_weights = normalise_kpi_weights(weights) if weights else None

    # user_ids controls rows displayed by the dashboard. Manager team members
    # are added to the calculation scope even when only the manager is filtered.
    display_user_ids = sorted({int(uid) for uid in user_ids or [] if uid})

    if display_user_ids:
        calculation_user_ids = set(display_user_ids)
        for manager_id in display_user_ids:
            manager_user = User.query.get(manager_id)
            profile_data = (
                _operations_kpi_profile_for_user(manager_user)
                if manager_user
                else {"include_indirect_reportees": True}
            )
            calculation_user_ids.update(
                _manager_team_user_ids(
                    manager_id,
                    include_indirect=profile_data["include_indirect_reportees"],
                )
            )
        calculation_user_ids = sorted(calculation_user_ids)
    else:
        calculation_user_ids = None

    entries = workload_entries_for_period(
        start_date,
        end_date,
        user_ids=calculation_user_ids,
        department=department,
        assigned_to_type="INTERNAL",
        include_vendors=False,
    )

    kpi_details_by_user = defaultdict(lambda: defaultdict(list))
    for entry in entries:
        assignment = entry.assignment
        if not assignment or not assignment.internal_user_id:
            continue
        service = entry.jobcard_service
        jobcard = service.jobcard if service else None
        minutes = _decimal(entry.calculated_minutes)
        completed = _assignment_is_completed(assignment)
        on_time = _assignment_completed_on_time(assignment) if completed else False
        kpi_details_by_user[assignment.internal_user_id][
            jobcard.id if jobcard else None
        ].append({
            "entry_id": entry.id,
            "assignment_id": assignment.id,
            "assignment_type": str(assignment.assignment_type or "PRODUCTION").upper(),
            "assignment_status": assignment.status or "Assigned",
            "assigned_at": assignment.assigned_at,
            "deadline": assignment.deadline,
            "completed_at": assignment.completed_at,
            "completed": completed,
            "on_time": on_time,
            "is_rework": bool(getattr(assignment, "is_rework_assignment", False)),
            "checklist_status": getattr(assignment, "checklist_status", None),
            "service": service.service_name if service and service.service_name else "Unspecified",
            "workload_master_service": entry.service_snapshot or "Unspecified",
            "application": entry.application_snapshot or "Unspecified",
            "file_extension": entry.file_extension_snapshot or "-",
            "sow": entry.sow_snapshot or "Unspecified",
            "complexity": entry.complexity_snapshot or "Unspecified",
            "unit_type": entry.unit_type_snapshot or "Quantity",
            "base_quantity": _quantize(entry.base_quantity_snapshot, FOUR_PLACES),
            "standard_minutes": _quantize(entry.standard_minutes_snapshot, FOUR_PLACES),
            "quantity": _quantize(entry.quantity, FOUR_PLACES),
            "calculated_minutes": _quantize(minutes, FOUR_PLACES),
            "calculated_hours": _hours(minutes),
            "calculation_rule": "({0} / {1}) x {2} = {3} minutes".format(
                _quantize(entry.quantity, FOUR_PLACES),
                _quantize(entry.base_quantity_snapshot, FOUR_PLACES),
                _quantize(entry.standard_minutes_snapshot, FOUR_PLACES),
                _quantize(minutes, FOUR_PLACES),
            ),
        })

    capacity = build_capacity_dashboard(
        start_date=start_date,
        end_date=end_date,
        user_ids=calculation_user_ids,
        department=department,
        capacity_overrides=capacity_overrides,
    )

    individual_rows_by_user: Dict[int, Dict[str, Any]] = {}

    for capacity_row in capacity["rows"]:
        user = capacity_row["user"]
        profile_data = _operations_kpi_profile_for_user(user)
        user_weights = explicit_weights or profile_data["weights"]
        metrics = _assignment_metrics_for_user(entries, user.id)

        workload_achievement = _percentage(
            metrics["completed_minutes"],
            metrics["total_minutes"],
        )
        on_time_completion = _percentage(
            metrics["on_time_assignments"],
            metrics["completed_assignments"],
        )
        utilisation_score = _quantize(
            _score_utilisation(capacity_row["utilisation_pct"]),
            TWO_PLACES,
        )
        rework_pct = _percentage(
            metrics["rework_minutes"],
            metrics["total_minutes"],
        )
        rework_control = max(ONE_HUNDRED - rework_pct, Decimal("0"))
        qc_compliance = (
            _percentage(metrics["qc_compliant"], metrics["qc_total"])
            if metrics["qc_total"] > 0
            else ONE_HUNDRED
        )

        component_scores = {
            "workload_achievement": workload_achievement,
            "on_time_completion": on_time_completion,
            "capacity_utilisation": utilisation_score,
            "rework_control": rework_control,
            "qc_compliance": qc_compliance,
        }

        individual_score = Decimal("0")
        for key, score in component_scores.items():
            individual_score += score * user_weights[key] / ONE_HUNDRED
        individual_score = min(
            max(individual_score, Decimal("0")),
            ONE_HUNDRED,
        )
        individual_score = _quantize(individual_score, TWO_PLACES)

        jobcard_details = []
        for jobcard_id, detail_rows in kpi_details_by_user.get(user.id, {}).items():
            jobcard = OperationsJobcard.query.get(jobcard_id) if jobcard_id else None
            jobcard_minutes = sum(
                (_decimal(item["calculated_minutes"]) for item in detail_rows),
                Decimal("0"),
            )
            completed_minutes_for_jobcard = sum(
                (
                    _decimal(item["calculated_minutes"])
                    for item in detail_rows
                    if item["completed"]
                ),
                Decimal("0"),
            )
            jobcard_details.append({
                "id": jobcard.id if jobcard else None,
                "code": jobcard.jobcard_code if jobcard else "Unknown Jobcard",
                "client": jobcard.client.company_name if jobcard and jobcard.client else "Unspecified Client",
                "status": jobcard.status if jobcard else None,
                "hours": _hours(jobcard_minutes),
                "completed_hours": _hours(completed_minutes_for_jobcard),
                "assignments": len({item["assignment_id"] for item in detail_rows}),
                "completed_assignments": len({
                    item["assignment_id"] for item in detail_rows if item["completed"]
                }),
                "on_time_assignments": len({
                    item["assignment_id"] for item in detail_rows if item["completed"] and item["on_time"]
                }),
                "rework_hours": _hours(sum(
                    (_decimal(item["calculated_minutes"]) for item in detail_rows if item["is_rework"]),
                    Decimal("0"),
                )),
                "details": detail_rows,
            })
        jobcard_details.sort(key=lambda item: _decimal(item["hours"]), reverse=True)

        weighted_components = {
            key: _quantize(component_scores[key] * user_weights[key] / ONE_HUNDRED, TWO_PLACES)
            for key in component_scores
        }

        individual_rows_by_user[user.id] = {
            "user": user,
            "user_id": user.id,
            "name": user.name,
            "email": user.email,
            "department": capacity_row.get("department"),
            "designation": (
                user.profile.designation.name
                if getattr(user, "profile", None)
                and getattr(user.profile, "designation", None)
                else None
            ),
            "kpi_profile_id": profile_data["id"],
            "kpi_profile_name": profile_data["name"],
            "kpi_weights": user_weights,
            "manager_weights": profile_data["manager_weights"],
            "include_indirect_reportees": profile_data["include_indirect_reportees"],
            "individual_score": individual_score,
            "score": individual_score,
            "final_score": individual_score,
            "team_score": None,
            "is_manager": False,
            "team_size": 0,
            "team_member_ids": [],
            "team_assigned_hours": Decimal("0.00"),
            "team_completed_hours": Decimal("0.00"),
            "workload_achievement_pct": workload_achievement,
            "on_time_completion_pct": on_time_completion,
            "capacity_utilisation_pct": capacity_row["utilisation_pct"],
            "capacity_utilisation_score": utilisation_score,
            "rework_pct": rework_pct,
            "rework_control_pct": rework_control,
            "qc_compliance_pct": qc_compliance,
            "assigned_hours": _hours(metrics["total_minutes"]),
            "completed_hours": _hours(metrics["completed_minutes"]),
            "assignment_count": metrics["assignment_count"],
            "completed_assignment_count": metrics["completed_assignments"],
            "on_time_assignment_count": metrics["on_time_assignments"],
            "status": _kpi_status(individual_score),
            "components": component_scores,
            "weighted_components": weighted_components,
            "jobcard_details": jobcard_details,
            "jobcard_count": len(jobcard_details),
            "capacity_hours": capacity_row["capacity_hours"],
            "remaining_hours": capacity_row["remaining_hours"],
            "over_capacity_hours": capacity_row["over_capacity_hours"],
            "kpi_explanation": {
                "workload": "Completed workload minutes / assigned workload minutes",
                "on_time": "Assignments completed by deadline / completed assignments",
                "utilisation": "Assigned workload hours / available capacity hours; 85-100% receives full component score",
                "rework": "100 - (rework workload minutes / assigned workload minutes)",
                "qc": "QC assignments with submitted/completed checklist / total QC assignments; no QC = 100%",
            },
        }

    # Add the team dependency after all individual scores are available. Team
    # score uses reportees' individual score to avoid recursive double counting.
    for user_id, row in individual_rows_by_user.items():
        reportee_ids = [
            reportee_id
            for reportee_id in _manager_team_user_ids(
                user_id,
                include_indirect=row["include_indirect_reportees"],
            )
            if reportee_id in individual_rows_by_user
        ]
        if not reportee_ids:
            continue

        weighted_total = Decimal("0")
        weight_total = Decimal("0")
        team_assigned = Decimal("0")
        team_completed = Decimal("0")

        for reportee_id in reportee_ids:
            member = individual_rows_by_user[reportee_id]
            assigned_hours = _decimal(member["assigned_hours"])
            completed_hours = _decimal(member["completed_hours"])
            # Prefer completed workload, then assigned workload, then one equal
            # vote so a new team member is still represented.
            member_weight = completed_hours or assigned_hours or Decimal("1")
            weighted_total += member["individual_score"] * member_weight
            weight_total += member_weight
            team_assigned += assigned_hours
            team_completed += completed_hours

        team_score = (
            weighted_total / weight_total
            if weight_total > 0
            else Decimal("0")
        )
        team_score = _quantize(team_score, TWO_PLACES)
        manager_weights = row["manager_weights"]
        final_score = (
            row["individual_score"] * manager_weights["individual"]
            + team_score * manager_weights["team"]
        ) / ONE_HUNDRED
        final_score = _quantize(
            min(max(final_score, Decimal("0")), ONE_HUNDRED),
            TWO_PLACES,
        )

        row.update({
            "is_manager": True,
            "team_score": team_score,
            "final_score": final_score,
            "score": final_score,
            "team_size": len(reportee_ids),
            "team_member_ids": reportee_ids,
            "team_assigned_hours": _quantize(team_assigned, TWO_PLACES),
            "team_completed_hours": _quantize(team_completed, TWO_PLACES),
            "status": _kpi_status(final_score),
        })

    if display_user_ids:
        rows = [
            individual_rows_by_user[user_id]
            for user_id in display_user_ids
            if user_id in individual_rows_by_user
        ]
    else:
        rows = list(individual_rows_by_user.values())

    rows.sort(key=lambda item: item["score"], reverse=True)
    for index, row in enumerate(rows, start=1):
        row["rank"] = index

    average_score = (
        sum((row["score"] for row in rows), Decimal("0"))
        / Decimal(len(rows))
        if rows
        else Decimal("0")
    )
    manager_rows = [row for row in rows if row["is_manager"]]
    average_team_score = (
        sum((row["team_score"] for row in manager_rows), Decimal("0"))
        / Decimal(len(manager_rows))
        if manager_rows
        else Decimal("0")
    )

    return {
        "period": {
            "start_date": start_date,
            "end_date": end_date,
        },
        "weights": normalise_kpi_weights(weights),
        "manager_weights": _manager_kpi_weights(),
        "manager_include_indirect_reportees": bool(
            current_app.config.get(
                "OPERATIONS_MANAGER_INCLUDE_INDIRECT_REPORTEES",
                True,
            )
        ),
        "uses_designation_profiles": True,
        "totals": {
            "employees": len(rows),
            "managers": len(manager_rows),
            "average_score": _quantize(average_score, TWO_PLACES),
            "average_team_score": _quantize(average_team_score, TWO_PLACES),
            "top_score": rows[0]["score"] if rows else Decimal("0.00"),
            "employees_above_90": sum(
                1 for row in rows if row["score"] >= Decimal("90")
            ),
            "employees_below_60": sum(
                1 for row in rows if row["score"] < Decimal("60")
            ),
        },
        "rows": rows,
        "leaderboard": rows[:10],
    }


def _kpi_status(score: Decimal) -> str:
    score = _decimal(score)
    if score >= Decimal("90"):
        return "Excellent"
    if score >= Decimal("75"):
        return "Good"
    if score >= Decimal("60"):
        return "Needs Attention"
    return "Critical"


# ---------------------------------------------------------------------------
# Filter helpers for routes/templates
# ---------------------------------------------------------------------------


def workload_filter_options() -> Dict[str, Any]:
    """Return distinct values used by dashboard filter dropdowns."""
    services = [
        row[0]
        for row in (
            db.session.query(OperationsJobcardWorkloadEntry.service_snapshot)
            .filter(OperationsJobcardWorkloadEntry.is_active.is_(True))
            .distinct()
            .order_by(OperationsJobcardWorkloadEntry.service_snapshot.asc())
            .all()
        )
        if row[0]
    ]

    applications = [
        row[0]
        for row in (
            db.session.query(OperationsJobcardWorkloadEntry.application_snapshot)
            .filter(OperationsJobcardWorkloadEntry.is_active.is_(True))
            .distinct()
            .order_by(OperationsJobcardWorkloadEntry.application_snapshot.asc())
            .all()
        )
        if row[0]
    ]

    sows = [
        row[0]
        for row in (
            db.session.query(OperationsJobcardWorkloadEntry.sow_snapshot)
            .filter(OperationsJobcardWorkloadEntry.is_active.is_(True))
            .distinct()
            .order_by(OperationsJobcardWorkloadEntry.sow_snapshot.asc())
            .all()
        )
        if row[0]
    ]

    departments = [
        row[0]
        for row in (
            db.session.query(EmployeeProfile.department)
            .filter(EmployeeProfile.department.isnot(None))
            .distinct()
            .order_by(EmployeeProfile.department.asc())
            .all()
        )
        if row[0]
    ]

    users = _operations_user_query().order_by(User.name.asc()).all()

    return {
        "services": services,
        "applications": applications,
        "sows": sows,
        "departments": departments,
        "users": users,
    }


__all__ = [
    "calculate_minutes",
    "create_workload_entry",
    "deactivate_workload_entry",
    "assignment_requires_workload",
    "required_assignments_for_jobcard",
    "missing_workload_assignments",
    "workload_completion_summary",
    "assignment_display_name",
    "team_user_ids",
    "direct_reportee_user_ids",
    "resolve_date_range",
    "month_bounds",
    "workload_entries_for_period",
    "build_workload_dashboard",
    "build_capacity_dashboard",
    "build_operations_kpi_dashboard",
    "workload_filter_options",
    "normalise_kpi_weights",
    "default_capacity_minutes",
    "capacity_status",
]
