"""Project Management workload, capacity and KPI calculations.

This module is intentionally separate from Operations workload calculations.
It reads existing jobcards, service quantities, billing records, closure margin
snapshots and rework tickets, but does not update any of those processes.
"""
from collections import defaultdict, deque
from datetime import date, datetime, time, timedelta
from decimal import Decimal, InvalidOperation, ROUND_CEILING, ROUND_HALF_UP
from typing import Any, Dict, Iterable, Optional, Sequence

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

from app import db
from app.models import (
    CurrencyRateMaster, EmployeeProfile, Invoice, OperationsJobcard,
    OperationsJobcardAssignment,
    OperationsJobcardClosureApprovalRequest,
    OperationsJobcardProcess,
    OperationsJobcardProcessAssignment,
    OperationsJobcardReopenRequest, OperationsJobcardService,
    OperationsReworkTicket, PmKpiProfile, PmServiceProductivityStandard,
    ProformaInvoice, Quote, User, VendorMaster, WorkforceGroup,
)

PM_WORKFORCE_CODE = "PM"
D = Decimal
TWO = D("0.01")
FOUR = D("0.0001")
HUNDRED = D("100")


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


def q(value: Any, places=TWO) -> Decimal:
    return dec(value).quantize(places, rounding=ROUND_HALF_UP)


def pct(num: Any, den: Any) -> Decimal:
    den = dec(den)
    return q(dec(num) * HUNDRED / den) if den > 0 else D("0.00")


def month_range(year=None, month=None, start_date=None, end_date=None):
    today = date.today()
    if start_date and end_date:
        return start_date, end_date
    year, month = int(year or today.year), int(month or today.month)
    start = date(year, month, 1)
    nxt = date(year + (month == 12), 1 if month == 12 else month + 1, 1)
    return start, nxt - timedelta(days=1)


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


def pm_user_query():
    return (User.query.join(WorkforceGroup, User.workforce_group_id == WorkforceGroup.id)
            .filter(User.is_active.is_(True), WorkforceGroup.code == PM_WORKFORCE_CODE,
                    WorkforceGroup.is_active.is_(True)))


def pm_team_user_ids(manager_id: int, include_indirect=True):
    allowed = {u.id for u in pm_user_query().all()}
    if manager_id not in allowed:
        return []
    children = defaultdict(list)
    rows = (db.session.query(EmployeeProfile.user_id, EmployeeProfile.reporting_manager_user_id)
            .filter(EmployeeProfile.user_id.in_(allowed)).all())
    for uid, mid in rows:
        if uid and mid:
            children[mid].append(uid)
    result, queue = [], deque(children.get(manager_id, []))
    seen = {manager_id}
    while queue:
        uid = queue.popleft()
        if uid in seen:
            continue
        seen.add(uid); result.append(uid)
        if include_indirect:
            queue.extend(children.get(uid, []))
    return result


def _is_admin_user(user):
    """
    Detect an Admin login without using operations.jobcard.view_all.

    PM KPI visibility must not use view_all because Team Leads may legitimately
    have that permission for Operations/jobcard access while still needing to
    see only themselves and their PM reporting hierarchy.

    Supports the role shapes used across Crystal Nexus:
      * user.is_admin boolean/property, when available
      * user.role as a string
      * user.role.name / user.role.code relationship
      * user.roles collection, when available
    """
    if not user:
        return False

    is_admin_attr = getattr(user, "is_admin", False)
    try:
        if callable(is_admin_attr):
            if bool(is_admin_attr()):
                return True
        elif bool(is_admin_attr):
            return True
    except Exception:
        pass

    admin_values = {"ADMIN", "ADMINISTRATOR", "SUPER ADMIN", "SUPERADMIN"}

    role = getattr(user, "role", None)

    if isinstance(role, str):
        if role.strip().upper() in admin_values:
            return True
    elif role is not None:
        for attr in ("name", "code", "role_name"):
            value = getattr(role, attr, None)
            if value and str(value).strip().upper() in admin_values:
                return True

    roles = getattr(user, "roles", None)
    if roles is not None:
        try:
            for row in roles:
                for attr in ("name", "code", "role_name"):
                    value = getattr(row, attr, None)
                    if value and str(value).strip().upper() in admin_values:
                        return True
        except Exception:
            pass

    return False


def visible_pm_user_ids(current_user):
    """
    PM dashboard visibility:

      Admin
        -> all active PM workforce users.

      PM Team Lead
        -> self + all direct/indirect PM reportees.

      PM member
        -> self only.

    Important:
    operations.jobcard.view_all is deliberately NOT used here. It controls
    jobcard access, not PM KPI reporting scope.
    """
    all_pm_ids = {u.id for u in pm_user_query().all()}

    if _is_admin_user(current_user):
        return sorted(all_pm_ids)

    # A non-PM user who is not Admin should not inherit visibility merely
    # because they have broad jobcard permissions.
    if current_user.id not in all_pm_ids:
        return []

    team_ids = pm_team_user_ids(current_user.id, True)

    if team_ids:
        return sorted(
            {current_user.id}.union(
                uid for uid in team_ids if uid in all_pm_ids
            )
        )

    return [current_user.id]


def filter_options(visible_ids=None):
    query = pm_user_query().options(joinedload(User.profile))
    if visible_ids is not None:
        query = query.filter(User.id.in_(visible_ids or [-1]))
    users = query.order_by(User.name.asc()).all()
    services = [r[0] for r in db.session.query(OperationsJobcardService.service_name)
                .filter(OperationsJobcardService.service_name.isnot(None)).distinct().order_by(OperationsJobcardService.service_name).all()]
    return {"users": users, "services": services,
            "departments": sorted({u.profile.department for u in users if u.profile and u.profile.department})}


def _normalize_service_name(value):
    """
    Normalize service labels used in jobcards and the PM productivity master.

    This prevents small naming differences such as:
      Proofread / Proof Reading / Proofreading
      VoiceOver / Voice Over
      Data Service / Data Services
    from bypassing the configured productivity standard.
    """
    raw = str(value or "").strip().lower()
    compact = "".join(ch for ch in raw if ch.isalnum())

    aliases = {
        "translation": "translation",
        "proofread": "proofreading",
        "proofreading": "proofreading",
        "proofreader": "proofreading",
        "subtitling": "subtitling",
        "subtitle": "subtitling",
        "multilingualstaffing": "multilingualstaffing",
        "multilingualstaff": "multilingualstaffing",
        "dataservice": "dataservices",
        "dataservices": "dataservices",
        "dataannotation": "dataservices",
        "voiceover": "voiceover",
        "interpretation": "interpretation",
        "interpreting": "interpretation",
        "transcription": "transcription",
        "dtp": "dtp",
        "filecreation": "filecreation",
        "fileformatting": "fileformatting",
    }
    return aliases.get(compact, compact)


def _active_standard(service_name, as_of):
    """
    Return the active productivity standard using normalized service matching.

    Matching in Python is intentional because MariaDB/MySQL service labels may
    contain spaces, hyphens, or minor naming variants that are cumbersome to
    normalize consistently in SQL across supported database versions.
    """
    wanted = _normalize_service_name(service_name)

    standards = (
        PmServiceProductivityStandard.query
        .filter(
            PmServiceProductivityStandard.is_active.is_(True),
            or_(
                PmServiceProductivityStandard.effective_from.is_(None),
                PmServiceProductivityStandard.effective_from <= as_of,
            ),
            or_(
                PmServiceProductivityStandard.effective_to.is_(None),
                PmServiceProductivityStandard.effective_to >= as_of,
            ),
        )
        .order_by(
            PmServiceProductivityStandard.effective_from.desc(),
            PmServiceProductivityStandard.id.desc(),
        )
        .all()
    )

    for standard in standards:
        canonical_name = (
            standard.service.name
            if getattr(standard, "service", None)
            else standard.service_name
        )
        if _normalize_service_name(canonical_name) == wanted:
            return standard

    return None


def _service_quantity(svc):
    if dec(svc.total_quantity) > 0:
        return dec(svc.total_quantity)
    if svc.quote_item and dec(svc.quote_item.qty) > 0:
        return dec(svc.quote_item.qty)
    return D("1")


def _pm_id(jobcard):
    return jobcard.current_owner_id or jobcard.assigned_to_id


def _completed(svc):
    return bool(svc.completed_at) or str(svc.status or "").strip().lower() in {"completed", "done", "ready for billing"}


def _deadline(svc):
    """Return the client-committed deadline for the service jobcard.

    PM on-time KPI deliberately ignores Production, QC and vendor assignment
    deadlines. The client deadline is captured during Assign Ops, stored on the
    quote and copied to the jobcard when it is created.
    """
    jobcard = getattr(svc, "jobcard", None)
    if not jobcard:
        return None

    deadline = getattr(jobcard, "client_deadline", None)
    if deadline:
        return deadline

    quote = getattr(jobcard, "quote", None)
    return getattr(quote, "client_deadline", None) if quote else None


def _currency_code(value):
    """Return a normalized three-letter currency code."""
    code = str(value or "INR").strip().upper()
    return {"EURO": "EUR", "EUROS": "EUR", "€": "EUR"}.get(code, code)


def _currency_to_inr_rate(currency_code, conversion_date=None):
    """
    Return the configured INR rate for one unit of the source currency.

    Rates are taken from currency_rate_master for the month and year of the
    related Invoice, Proforma Invoice, or Ready-for-Billing transaction.
    INR always uses a rate of 1.
    """
    code = _currency_code(currency_code)

    if code == "INR":
        return D("1")

    conversion_date = conversion_date or date.today()

    # Accept both date and datetime values.
    year = conversion_date.year
    month = conversion_date.month

    row = (
        CurrencyRateMaster.query
        .filter(
            CurrencyRateMaster.year == year,
            CurrencyRateMaster.month == month,
            func.upper(CurrencyRateMaster.currency_code) == code,
        )
        .first()
    )

    if row and dec(row.rate_to_inr) > 0:
        return dec(row.rate_to_inr)

    return None


def _amount_to_inr(amount, currency_code, conversion_date=None):
    """
    Convert an amount to INR using CurrencyRateMaster.

    A missing foreign-currency rate returns None so that the amount is not
    incorrectly treated as INR.
    """
    rate = _currency_to_inr_rate(currency_code, conversion_date)
    if rate is None:
        return None
    return q(dec(amount) * rate)


def _as_date(value):
    """Normalize a date/datetime value to a date for KPI period checks."""
    if isinstance(value, datetime):
        return value.date()
    return value if isinstance(value, date) else None


def _date_in_period(value, start_date, end_date):
    value = _as_date(value)
    return bool(value and start_date <= value <= end_date)


def _jobcard_revenue_event(jobcard):
    """Return (amount_inr, source, event_date) for the current revenue source.

    PM Revenue KPI is event based.  The current source priority is deliberately
    retained (Invoice -> PI -> Ready for Billing), but the source contributes
    only in the period containing its own transaction date.  This prevents a
    July-created jobcard from automatically contributing revenue to July.
    """
    if getattr(jobcard, "is_sample_job", False) or str(jobcard.status or "").strip().lower() == "sample completed":
        return D(0), "Sample Job - Non-Billable", None

    inv = (
        Invoice.query
        .filter(
            Invoice.jobcard_id == jobcard.id,
            func.lower(Invoice.status) != "cancelled",
            Invoice.is_cancelled.is_(False),
        )
        .order_by(Invoice.invoice_date.desc(), Invoice.id.desc())
        .first()
    )

    if inv:
        event_date = inv.invoice_date or _as_date(inv.created_at)
        source_amount = dec(inv.subtotal or inv.total_amount)
        amount_inr = _amount_to_inr(
            source_amount, inv.currency, event_date or date.today()
        )
        if amount_inr is None:
            return (D("0"),
                    "Invoice - Missing INR rate for {0}".format(_currency_code(inv.currency)),
                    event_date)
        return amount_inr, "Invoice", event_date

    pi = (
        ProformaInvoice.query
        .filter(
            ProformaInvoice.quote_id == jobcard.quote_id,
            ProformaInvoice.is_cancelled.is_(False),
        )
        .order_by(ProformaInvoice.pi_date.desc(), ProformaInvoice.id.desc())
        .first()
    )

    if pi:
        event_date = pi.pi_date or _as_date(pi.created_at)
        source_amount = dec(pi.subtotal or pi.total_amount)
        amount_inr = _amount_to_inr(
            source_amount, pi.currency, event_date or date.today()
        )
        if amount_inr is None:
            return (D("0"),
                    "Proforma Invoice - Missing INR rate for {0}".format(_currency_code(pi.currency)),
                    event_date)
        return amount_inr, "Proforma Invoice", event_date

    if (
        str(jobcard.status or "").strip().lower() == "ready for billing"
        and jobcard.quote
    ):
        quote = jobcard.quote
        event_date = _as_date(jobcard.ready_for_billing_at)
        source_amount = dec(
            quote.subtotal
            or getattr(quote, "total_amount", None)
            or quote.total
        )
        conversion_date = event_date or _as_date(getattr(quote, "created_at", None)) or _as_date(jobcard.created_at) or date.today()
        amount_inr = _amount_to_inr(source_amount, quote.currency, conversion_date)
        if amount_inr is None:
            return (D("0"),
                    "Ready for Billing - Missing INR rate for {0}".format(_currency_code(quote.currency)),
                    event_date)
        return amount_inr, "Ready for Billing", event_date

    return D("0"), "Not Eligible", None


def _jobcard_revenue(jobcard):
    """Backward-compatible revenue accessor used outside the period split."""
    amount, source, _event_date = _jobcard_revenue_event(jobcard)
    return amount, source


def _revenue_event_candidate_jobcard_ids(start_date, end_date):
    """Return jobcards that may have a billing/revenue event in the period."""
    invoice_ids = {
        row[0] for row in (
            db.session.query(Invoice.jobcard_id)
            .filter(
                Invoice.jobcard_id.isnot(None),
                Invoice.invoice_date >= start_date,
                Invoice.invoice_date <= end_date,
                func.lower(Invoice.status) != "cancelled",
                Invoice.is_cancelled.is_(False),
            ).distinct().all()
        ) if row[0]
    }

    pi_quote_ids = {
        row[0] for row in (
            db.session.query(ProformaInvoice.quote_id)
            .filter(
                ProformaInvoice.pi_date >= start_date,
                ProformaInvoice.pi_date <= end_date,
                ProformaInvoice.is_cancelled.is_(False),
            ).distinct().all()
        ) if row[0]
    }
    pi_jobcard_ids = set()
    if pi_quote_ids:
        pi_jobcard_ids = {
            row[0] for row in (
                db.session.query(OperationsJobcard.id)
                .filter(OperationsJobcard.quote_id.in_(pi_quote_ids))
                .distinct().all()
            ) if row[0]
        }

    start_dt = datetime.combine(start_date, time.min)
    end_dt = datetime.combine(end_date + timedelta(days=1), time.min)
    rfb_ids = {
        row[0] for row in (
            db.session.query(OperationsJobcard.id)
            .filter(
                OperationsJobcard.ready_for_billing_at >= start_dt,
                OperationsJobcard.ready_for_billing_at < end_dt,
            ).distinct().all()
        ) if row[0]
    }

    return invoice_ids | pi_jobcard_ids | rfb_ids


def _vendor_currency(assignment):
    """Return the currency configured against an external vendor assignment."""
    vendor = getattr(assignment, "vendor", None)

    if vendor is None and getattr(assignment, "vendor_id", None):
        vendor = VendorMaster.query.get(assignment.vendor_id)

    return _currency_code(getattr(vendor, "currency", None))


def _jobcard_margin_details(jobcard):
    """
    Calculate the current jobcard margin in INR.

    The previous implementation read only
    OperationsJobcardClosureApprovalRequest.profit_margin_pct. That table is
    generally populated only when a low-margin closure approval is needed, so
    ordinary/high-margin jobcards appeared blank in the PM KPI.

    This calculation mirrors the Operations commercial overview:
      * quote subtotal is converted to INR;
      * all active external Production assignment costs are converted to INR;
      * all active external internal-process costs are converted to INR;
      * margin is calculated from the complete jobcard commercial value.

    A saved closure snapshot remains a fallback when a live calculation cannot
    be completed because the quote value or a currency rate is unavailable.
    """
    if getattr(jobcard, "is_sample_job", False) or str(jobcard.status or "").strip().lower() == "sample completed":
        return {
            "margin_pct": None,
            "commercial_value_inr": D(0),
            "vendor_cost_inr": D(0),
            "profit_amount_inr": D(0),
            "source": "Sample Job - Not Applicable",
        }

    quote = getattr(jobcard, "quote", None)

    quote_currency = _currency_code(
        getattr(quote, "currency", None) if quote else "INR"
    )
    quote_amount_original = dec(
        getattr(quote, "subtotal", None)
        if quote else 0
    )
    quote_conversion_date = (
        getattr(quote, "created_at", None)
        if quote and getattr(quote, "created_at", None)
        else getattr(jobcard, "created_at", None)
        or date.today()
    )

    quote_amount_inr = _amount_to_inr(
        quote_amount_original,
        quote_currency,
        quote_conversion_date,
    )

    missing_rates = []
    if quote_amount_inr is None:
        missing_rates.append(quote_currency)
        quote_amount_inr = D("0")

    total_vendor_cost_inr = D("0")

    service_assignments = (
        OperationsJobcardAssignment.query
        .join(
            OperationsJobcardService,
            OperationsJobcardService.id
            == OperationsJobcardAssignment.jobcard_service_id,
        )
        .filter(
            OperationsJobcardService.jobcard_id == jobcard.id,
            OperationsJobcardAssignment.assignment_type == "PRODUCTION",
            OperationsJobcardAssignment.assigned_to_type == "VENDOR",
            OperationsJobcardAssignment.status.notin_(
                ["Replaced", "Cancelled"]
            ),
        )
        .all()
    )

    for assignment in service_assignments:
        qty = dec(assignment.assigned_qty)
        rate = dec(assignment.rate)
        original_cost = rate if assignment.flat_rate else qty * rate
        currency = _vendor_currency(assignment)
        conversion_date = (
            getattr(assignment, "created_at", None)
            or getattr(jobcard, "created_at", None)
            or date.today()
        )
        cost_inr = _amount_to_inr(
            original_cost,
            currency,
            conversion_date,
        )
        if cost_inr is None:
            missing_rates.append(currency)
            continue
        total_vendor_cost_inr += cost_inr

    process_assignments = (
        OperationsJobcardProcessAssignment.query
        .join(
            OperationsJobcardProcess,
            OperationsJobcardProcess.id
            == OperationsJobcardProcessAssignment.jobcard_process_id,
        )
        .filter(
            OperationsJobcardProcess.jobcard_id == jobcard.id,
            OperationsJobcardProcessAssignment.assigned_to_type == "VENDOR",
            OperationsJobcardProcessAssignment.status.notin_(["Cancelled"]),
        )
        .all()
    )

    for assignment in process_assignments:
        qty = dec(assignment.assigned_qty)
        rate = dec(assignment.rate)
        original_cost = rate if assignment.flat_rate else qty * rate
        currency = _vendor_currency(assignment)
        conversion_date = (
            getattr(assignment, "created_at", None)
            or getattr(jobcard, "created_at", None)
            or date.today()
        )
        cost_inr = _amount_to_inr(
            original_cost,
            currency,
            conversion_date,
        )
        if cost_inr is None:
            missing_rates.append(currency)
            continue
        total_vendor_cost_inr += cost_inr

    if quote_amount_inr > 0 and not missing_rates:
        profit_amount_inr = quote_amount_inr - total_vendor_cost_inr
        margin_pct = profit_amount_inr * HUNDRED / quote_amount_inr
        return {
            "margin_pct": q(margin_pct),
            "commercial_value_inr": q(quote_amount_inr),
            "vendor_cost_inr": q(total_vendor_cost_inr),
            "profit_amount_inr": q(profit_amount_inr),
            "source": "Live commercial calculation",
            "missing_rates": [],
        }

    snapshot = (
        OperationsJobcardClosureApprovalRequest.query
        .filter_by(jobcard_id=jobcard.id)
        .filter(
            OperationsJobcardClosureApprovalRequest.status.in_(
                ["Approved", "Pending"]
            )
        )
        .order_by(OperationsJobcardClosureApprovalRequest.id.desc())
        .first()
    )

    if snapshot and snapshot.profit_margin_pct is not None:
        snapshot_value = dec(snapshot.quote_amount_ex_tax)
        return {
            "margin_pct": q(snapshot.profit_margin_pct),
            "commercial_value_inr": q(snapshot_value),
            "vendor_cost_inr": q(snapshot.total_vendor_costs),
            "profit_amount_inr": q(snapshot.profit_amount),
            "source": "Closure margin snapshot",
            "missing_rates": sorted(set(missing_rates)),
        }

    return {
        "margin_pct": None,
        "commercial_value_inr": q(quote_amount_inr),
        "vendor_cost_inr": q(total_vendor_cost_inr),
        "profit_amount_inr": None,
        "source": (
            "Missing INR rate: {0}".format(
                ", ".join(sorted(set(missing_rates)))
            )
            if missing_rates
            else "Margin unavailable"
        ),
        "missing_rates": sorted(set(missing_rates)),
    }


def _jobcard_margin(jobcard):
    """Backward-compatible margin accessor."""
    return _jobcard_margin_details(jobcard)["margin_pct"]


def _profile_for(user):
    did = user.profile.designation_id if user.profile else None
    row = PmKpiProfile.query.filter_by(user_id=user.id, is_active=True).first()
    if row is None and did:
        row = PmKpiProfile.query.filter_by(designation_id=did, user_id=None, is_active=True).first()
    if row is None:
        row = PmKpiProfile.query.filter_by(is_default=True, user_id=None, designation_id=None, is_active=True).order_by(PmKpiProfile.id).first()
    return row


def _profile_data(row):
    return {
        "name": row.profile_name if row else "System Default",
        "weights": {
            "projects": dec(row.projects_executed_weight if row else 40),
            "revenue": dec(row.revenue_generated_weight if row else 20),
            "margin": dec(row.profit_margin_weight if row else 20),
            "on_time": dec(row.on_time_delivery_weight if row else 15),
            "rework": dec(row.rework_control_weight if row else 5),
        },
        "revenue_multiplier": dec(row.revenue_ctc_multiplier if row else 30),
        "margin_target": dec(row.minimum_profit_margin_pct if row else 50),
        "on_time_target": dec(row.on_time_target_pct if row else 99),
        "rework_limit": dec(row.maximum_rework_pct if row else 5),
        "ticket1": int(row.ticket_first_threshold if row else 1),
        "ticket2": int(row.ticket_second_threshold if row else 6),
        "deduction1": dec(row.ticket_first_deduction if row else 5),
        "deduction2": dec(row.ticket_second_deduction if row else 10),
        "tl_individual": dec(row.tl_individual_weight if row else 40),
        "tl_team": dec(row.tl_team_weight if row else 60),
        "include_indirect": bool(row.include_indirect_reportees) if row else True,
    }


def _raw_rows(start_date, end_date, user_ids=None, service_name=None, department=None, active_only=False, period_mode="created", jobcard_ids=None):
    """Build PM service rows for a selected population.

    period_mode:
      created  - legacy/current workload population: jobcard created in period
      overlap  - jobcard was open/active at some point in the selected period
      closed   - jobcard closed in the selected period
      any      - no date filter; normally paired with explicit jobcard_ids
    """
    start_dt = datetime.combine(start_date, time.min)
    end_dt = datetime.combine(end_date + timedelta(days=1), time.min)
    query = (OperationsJobcardService.query.join(OperationsJobcard)
             .options(joinedload(OperationsJobcardService.jobcard).joinedload(OperationsJobcard.assigned_to),
                      joinedload(OperationsJobcardService.quote_item)))

    if jobcard_ids is not None:
        query = query.filter(OperationsJobcard.id.in_(jobcard_ids or [-1]))

    if period_mode == "created":
        query = query.filter(
            OperationsJobcard.created_at >= start_dt,
            OperationsJobcard.created_at < end_dt,
        )
    elif period_mode == "overlap":
        query = query.filter(
            OperationsJobcard.created_at < end_dt,
            or_(
                OperationsJobcard.closed_at.is_(None),
                OperationsJobcard.closed_at >= start_dt,
            ),
        )
    elif period_mode == "closed":
        query = query.filter(
            OperationsJobcard.closed_at >= start_dt,
            OperationsJobcard.closed_at < end_dt,
        )
    elif period_mode != "any":
        raise ValueError("Unsupported PM KPI period mode: {0}".format(period_mode))
    if user_ids is not None:
        query = query.filter(or_(OperationsJobcard.current_owner_id.in_(user_ids or [-1]), OperationsJobcard.assigned_to_id.in_(user_ids or [-1])))
    if service_name:
        query = query.filter(func.lower(OperationsJobcardService.service_name) == service_name.lower())

    service_rows = query.all()

    # Workload and Capacity represent current active work only. KPI continues
    # to call this function with active_only=False and therefore retains its
    # historical/completed dataset.
    invoiced_jobcard_ids = set()
    pi_quote_ids = set()

    if active_only and service_rows:
        jobcard_ids = {
            svc.jobcard_id
            for svc in service_rows
            if svc.jobcard_id
        }
        quote_ids = {
            svc.jobcard.quote_id
            for svc in service_rows
            if svc.jobcard and svc.jobcard.quote_id
        }

        if jobcard_ids:
            invoiced_jobcard_ids = {
                row[0]
                for row in (
                    db.session.query(Invoice.jobcard_id)
                    .filter(
                        Invoice.jobcard_id.in_(jobcard_ids),
                        Invoice.is_cancelled.is_(False),
                        func.lower(Invoice.status) != "cancelled",
                    )
                    .distinct()
                    .all()
                )
                if row[0]
            }

        if quote_ids:
            pi_quote_ids = {
                row[0]
                for row in (
                    db.session.query(ProformaInvoice.quote_id)
                    .filter(
                        ProformaInvoice.quote_id.in_(quote_ids),
                        ProformaInvoice.is_cancelled.is_(False),
                    )
                    .distinct()
                    .all()
                )
                if row[0]
            }

    rows=[]
    for svc in service_rows:
        if active_only:
            jobcard = svc.jobcard
            status_key = str(jobcard.status or "").strip().lower()

            completed_statuses = {
                "ready for billing",
                "ready for invoicing",
                "pi raised",
                "proforma invoice raised",
                "invoice raised",
                "invoiced",
                "completed",
                "closed",
                "cancelled",
                "canceled",
            }

            is_billed = (
                jobcard.id in invoiced_jobcard_ids
                or (
                    jobcard.quote_id
                    and jobcard.quote_id in pi_quote_ids
                )
            )
            is_closed = bool(getattr(jobcard, "closed_at", None))

            if is_billed or is_closed or status_key in completed_statuses:
                continue
        pmid=_pm_id(svc.jobcard)
        user=User.query.get(pmid) if pmid else None
        if not user or not user.workforce_group or user.workforce_group.code != PM_WORKFORCE_CODE:
            continue
        if department and (not user.profile or user.profile.department != department):
            continue
        standard=_active_standard(svc.service_name, end_date)
        qty=_service_quantity(svc)
        qpp = max(
            dec(standard.quantity_per_project if standard else 1),
            D("0.0001"),
        )

        # One partially used project still consumes one project slot.
        #
        # Examples:
        #   Translation: 5,500 / 5,000 = 1.10 -> 2 projects
        #   Translation: 5,000 / 5,000 = 1.00 -> 1 project
        #   Proof Reading: 8,000 / 7,500 = 1.07 -> 2 projects
        #
        # The ceiling is applied per jobcard service line, as requested.
        if standard:
            projects = (
                (qty / qpp).quantize(D("1"), rounding=ROUND_CEILING)
                if qty > 0
                else D("0")
            )
        else:
            # When no PM productivity standard exists, every jobcard line
            # item counts as one project irrespective of its raw quantity.
            projects = D("1")
        projects = q(projects, FOUR)

        minutes = q(
            projects
            * dec(
                standard.minutes_per_project
                if standard
                else 480
            ),
            FOUR,
        )
        deadline = _deadline(svc)
        completed = _completed(svc)

        # PM on-time delivery is a jobcard-level client commitment.
        # Compare dates only, as requested:
        #     jobcard.closed_at DATE <= client_deadline DATE
        #
        # Service completed_at and assignment deadlines are intentionally not
        # used for this KPI.
        jobcard_closed_at = getattr(svc.jobcard, "closed_at", None)
        deadline_date = deadline.date() if deadline else None
        closed_date = (
            jobcard_closed_at.date()
            if jobcard_closed_at
            else None
        )

        on_time_eligible = bool(
            deadline_date
            and closed_date
        )
        on_time = bool(
            on_time_eligible
            and closed_date <= deadline_date
        )

        overdue = bool(
            deadline_date
            and not closed_date
            and deadline_date < datetime.utcnow().date()
        )

        rows.append({
            "service": svc,
            "jobcard": svc.jobcard,
            "user": user,
            "quantity": qty,
            "projects": projects,
            "minutes": minutes,
            "standard": standard,
            "quantity_per_project": qpp if standard else None,
            "minutes_per_project": dec(
                standard.minutes_per_project if standard else 480
            ),
            "calculation_rule": (
                "CEILING({0} / {1}) = {2}".format(
                    q(qty, FOUR),
                    q(qpp, FOUR),
                    q(projects, FOUR),
                )
                if standard
                else "No standard: 1 line item = 1 project"
            ),
            "completed": completed,
            "on_time": on_time,
            "on_time_eligible": on_time_eligible,
            "deadline": deadline,
            "deadline_date": deadline_date,
            "closed_at": jobcard_closed_at,
            "closed_date": closed_date,
            "overdue": overdue,
        })

    return rows


def _standard_label(row):
    standard = row.get("standard")
    if standard and getattr(standard, "service", None):
        return standard.service.name
    if standard and standard.service_name:
        return standard.service_name
    return row["service"].service_name or "Unspecified"


def _line_item_name(svc):
    quote_item = getattr(svc, "quote_item", None)
    if not quote_item:
        return svc.service_name or "Line item"
    return (
        getattr(quote_item, "description", None)
        or getattr(quote_item, "item_name", None)
        or getattr(quote_item, "service_name", None)
        or svc.service_name
        or "Line item"
    )


def build_workload_dashboard(start_date, end_date, user_ids=None, service_name=None, department=None):
    """Build current PM workload using the KPI line-item engine.

    Only active jobcards are included. Closed, completed, Ready for Billing,
    PI-raised, invoiced and cancelled jobcards are excluded.
    """
    rows = _raw_rows(
        start_date,
        end_date,
        user_ids,
        service_name,
        department,
        active_only=True,
    )
    days = working_days(start_date, end_date)

    by_user = defaultdict(lambda: {
        "quantity": D(0), "projects": D(0), "minutes": D(0),
        "completed": D(0), "on_time_eligible": D(0), "on_time": D(0),
        "overdue": D(0), "jobcards": set(), "line_items": 0,
        "details": defaultdict(lambda: {
            "quantity": D(0), "projects": D(0), "minutes": D(0),
            "services": set(), "line_items": []
        }),
    })
    by_service = defaultdict(lambda: {
        "quantity": D(0), "projects": D(0), "minutes": D(0),
        "jobcards": set(), "line_items": 0,
    })

    for row in rows:
        uid = row["user"].id
        service_label = _standard_label(row)
        user_bucket = by_user[uid]
        service_bucket = by_service[service_label]

        for bucket in (user_bucket, service_bucket):
            bucket["quantity"] += row["quantity"]
            bucket["projects"] += row["projects"]
            bucket["minutes"] += row["minutes"]
            bucket["jobcards"].add(row["jobcard"].id)
            bucket["line_items"] += 1

        if row["completed"]:
            user_bucket["completed"] += row["projects"]
        if row.get("on_time_eligible"):
            user_bucket["on_time_eligible"] += row["projects"]
        if row["on_time"]:
            user_bucket["on_time"] += row["projects"]
        if row["overdue"]:
            user_bucket["overdue"] += row["projects"]

        detail = user_bucket["details"][row["jobcard"].id]
        detail["jobcard"] = row["jobcard"]
        detail["quantity"] += row["quantity"]
        detail["projects"] += row["projects"]
        detail["minutes"] += row["minutes"]
        detail["services"].add(service_label)
        detail["line_items"].append({
            "service": service_label,
            "line_item": _line_item_name(row["service"]),
            "quantity": q(row["quantity"], FOUR),
            "quantity_per_project": (
                q(row["quantity_per_project"], FOUR)
                if row.get("quantity_per_project") is not None else None
            ),
            "projects": q(row["projects"], FOUR),
            "minutes_per_project": q(row["minutes_per_project"]),
            "effort_minutes": q(row["minutes"]),
            "calculation_rule": row["calculation_rule"],
        })

    employees = []
    for uid, values in by_user.items():
        user = User.query.get(uid)
        available_minutes = D(days * 8 * 60)
        average_minutes = (
            values["minutes"] / values["projects"]
            if values["projects"] > 0 else D(0)
        )
        required_projects = (
            available_minutes / average_minutes
            if average_minutes > 0 else D(0)
        )
        assigned_hours = values["minutes"] / D(60)
        capacity_hours = D(days * 8)

        jobcards = []
        for detail in values["details"].values():
            jc = detail["jobcard"]
            jobcards.append({
                "id": jc.id,
                "code": jc.jobcard_code,
                "created_at": jc.created_at.strftime("%d-%m-%Y") if jc.created_at else "—",
                "status": jc.status or "—",
                "services": ", ".join(sorted(detail["services"])),
                "quantity": q(detail["quantity"]),
                "projects": q(detail["projects"]),
                "effort_hours": q(detail["minutes"] / D(60)),
                "line_items": detail["line_items"],
            })
        jobcards.sort(key=lambda item: item["code"] or "")

        employees.append({
            "id": uid,
            "name": user.name,
            "email": user.email,
            "department": user.profile.department if user.profile else None,
            "jobcards": len(values["jobcards"]),
            "line_items": values["line_items"],
            "quantity": q(values["quantity"]),
            "projects": q(values["projects"]),
            "hours": q(assigned_hours),
            "capacity_hours": q(capacity_hours),
            "remaining_hours": q(max(capacity_hours - assigned_hours, D(0))),
            "over_capacity_hours": q(max(assigned_hours - capacity_hours, D(0))),
            "utilisation_pct": pct(assigned_hours, capacity_hours),
            "average_minutes_per_project": q(average_minutes),
            "required_projects": q(required_projects),
            "has_workload_mix": values["projects"] > 0,
            "completed_projects": q(values["completed"]),
            "on_time_pct": pct(values["on_time"], values["on_time_eligible"]),
            "overdue_projects": q(values["overdue"]),
            "jobcard_details": jobcards,
        })

    employees.sort(key=lambda item: item["hours"], reverse=True)

    services = []
    for label, values in by_service.items():
        services.append({
            "label": label,
            "quantity": float(q(values["quantity"])),
            "projects": float(q(values["projects"])),
            "hours": float(q(values["minutes"] / D(60))),
            "jobcards": len(values["jobcards"]),
            "line_items": values["line_items"],
        })
    services.sort(key=lambda item: item["hours"], reverse=True)

    total_minutes = sum((row["minutes"] for row in rows), D(0))
    total_projects = sum((row["projects"] for row in rows), D(0))
    total_capacity = D(len(employees) * days * 8)
    total_hours = total_minutes / D(60)

    return {
        "working_days": days,
        "dataset_mode": "active",
        "excluded_stages": [
            "Ready For Billing",
            "PI Raised",
            "Invoice Raised",
            "Completed",
            "Closed",
            "Cancelled",
        ],
        "totals": {
            "users": len(employees),
            "jobcards": len({row["jobcard"].id for row in rows}),
            "line_items": len(rows),
            "quantity": q(sum((row["quantity"] for row in rows), D(0))),
            "projects": q(total_projects),
            "hours": q(total_hours),
            "capacity_hours": q(total_capacity),
            "remaining_hours": q(max(total_capacity - total_hours, D(0))),
            "utilisation_pct": pct(total_hours, total_capacity),
            "completed_projects": q(sum((row["projects"] for row in rows if row["completed"]), D(0))),
            "overdue_projects": q(sum((row["projects"] for row in rows if row["overdue"]), D(0))),
        },
        "employees": employees,
        "services": services,
    }


def build_capacity_dashboard(start_date, end_date, user_ids=None, service_name=None, department=None):
    """Capacity uses the same active-only workload dataset and KPI standards."""
    workload = build_workload_dashboard(
        start_date, end_date, user_ids, service_name, department
    )
    days = workload["working_days"]
    users = pm_user_query().options(joinedload(User.profile)).all()
    if user_ids is not None:
        allowed = set(user_ids)
        users = [user for user in users if user.id in allowed]
    if department:
        users = [
            user for user in users
            if user.profile and user.profile.department == department
        ]

    workload_by_id = {row["id"]: row for row in workload["employees"]}
    rows = []
    for user in users:
        wr = workload_by_id.get(user.id, {})
        capacity_hours = D(days * 8)
        assigned_hours = dec(wr.get("hours"))
        utilisation = pct(assigned_hours, capacity_hours)
        status = (
            "Available" if utilisation < 50 else
            "Light" if utilisation < 75 else
            "Moderate" if utilisation < 90 else
            "Heavy" if utilisation <= 100 else
            "Critical"
        )
        rows.append({
            "id": user.id,
            "name": user.name,
            "email": user.email,
            "department": user.profile.department if user.profile else None,
            "working_days": days,
            "capacity_hours": q(capacity_hours),
            "assigned_hours": q(assigned_hours),
            "remaining_hours": q(max(capacity_hours - assigned_hours, D(0))),
            "over_capacity_hours": q(max(assigned_hours - capacity_hours, D(0))),
            "utilisation_pct": utilisation,
            "status": status,
            "projects": dec(wr.get("projects")),
            "required_projects": dec(wr.get("required_projects")),
            "average_minutes_per_project": dec(wr.get("average_minutes_per_project")),
            "has_workload_mix": bool(wr.get("has_workload_mix")),
            "jobcards": int(wr.get("jobcards", 0)),
            "line_items": int(wr.get("line_items", 0)),
            "jobcard_details": wr.get("jobcard_details", []),
        })

    rows.sort(key=lambda item: item["utilisation_pct"], reverse=True)
    capacity = sum((dec(row["capacity_hours"]) for row in rows), D(0))
    assigned = sum((dec(row["assigned_hours"]) for row in rows), D(0))

    return {
        "working_days": days,
        "dataset_mode": "active",
        "excluded_stages": workload.get("excluded_stages", []),
        "totals": {
            "users": len(rows),
            "working_days": days,
            "capacity_hours": q(capacity),
            "assigned_hours": q(assigned),
            "remaining_hours": q(max(capacity - assigned, D(0))),
            "over_capacity_hours": q(max(assigned - capacity, D(0))),
            "utilisation_pct": pct(assigned, capacity),
            "critical_users": sum(row["status"] == "Critical" for row in rows),
            "projects": q(sum((dec(row["projects"]) for row in rows), D(0))),
            "jobcards": sum(row["jobcards"] for row in rows),
        },
        "rows": rows,
    }

def build_kpi_dashboard(start_date, end_date, user_ids=None, service_name=None, department=None):
    """Build the PM KPI using business-event dates instead of creation date.

    Period treatment is intentionally split by KPI component:
      * workload/capacity mix -> jobcards active at any point in the period
      * projects/margin/on-time -> jobcards closed in the period
      * revenue -> current Invoice / PI / Ready-for-Billing event date
      * rework -> rework ticket created date

    This means a jobcard created in July and closed in August remains visible as
    carried-forward work in August, while Projects, Margin and On-time are
    credited to August.  Revenue follows its own billing transaction month.
    """
    days = working_days(start_date, end_date)

    users = pm_user_query().options(joinedload(User.profile)).all()
    if user_ids is not None:
        allowed_ids = set(user_ids)
        users = [u for u in users if u.id in allowed_ids]
    if department:
        users = [u for u in users if u.profile and u.profile.department == department]

    users_by_id = {u.id: u for u in users}

    # 1) Workload/capacity population: anything that was open during the
    # selected period, including carried-forward jobs created earlier.
    activity_raw = _raw_rows(
        start_date, end_date, user_ids, service_name, department,
        period_mode="overlap",
    )

    # 2) Delivery-result population: only jobs actually closed in the period.
    closed_raw = _raw_rows(
        start_date, end_date, user_ids, service_name, department,
        period_mode="closed",
    )

    # 3) Revenue population: discover jobcards with a billing event in the
    # period, then verify the jobcard's *current* source priority/event date.
    revenue_candidate_ids = _revenue_event_candidate_jobcard_ids(
        start_date, end_date
    )
    revenue_raw = _raw_rows(
        start_date, end_date, user_ids, service_name, department,
        period_mode="any", jobcard_ids=revenue_candidate_ids,
    )

    # 4) Rework population: tickets are credited to the month in which the
    # ticket was raised, not the month the jobcard was created.
    start_dt = datetime.combine(start_date, time.min)
    end_dt = datetime.combine(end_date + timedelta(days=1), time.min)
    ticket_query = (
        OperationsReworkTicket.query
        .options(
            joinedload(OperationsReworkTicket.jobcard),
            joinedload(OperationsReworkTicket.jobcard_service),
        )
        .filter(
            OperationsReworkTicket.created_at >= start_dt,
            OperationsReworkTicket.created_at < end_dt,
        )
    )
    period_tickets = ticket_query.all()
    if service_name:
        period_tickets = [
            t for t in period_tickets
            if t.jobcard_service
            and str(t.jobcard_service.service_name or "").strip().lower()
            == service_name.strip().lower()
        ]

    # Keep only tickets whose PM falls inside the already-authorized PM set.
    period_tickets = [
        t for t in period_tickets
        if t.jobcard and _pm_id(t.jobcard) in users_by_id
    ]

    ticket_jobcard_ids = {t.jobcard_id for t in period_tickets if t.jobcard_id}
    ticket_detail_raw = _raw_rows(
        start_date, end_date, user_ids, service_name, department,
        period_mode="any", jobcard_ids=ticket_jobcard_ids,
    ) if ticket_jobcard_ids else []

    def group_by_pm(rows):
        grouped = defaultdict(list)
        for row in rows:
            uid = row['user'].id
            if uid in users_by_id:
                grouped[uid].append(row)
        return grouped

    activity_per = group_by_pm(activity_raw)
    closed_per = group_by_pm(closed_raw)
    revenue_per = group_by_pm(revenue_raw)
    ticket_detail_per = group_by_pm(ticket_detail_raw)

    tickets_per = defaultdict(list)
    for ticket in period_tickets:
        uid = _pm_id(ticket.jobcard)
        if uid in users_by_id:
            tickets_per[uid].append(ticket)

    def member_rows(grouped, member_ids):
        result = []
        for uid in member_ids:
            result.extend(grouped.get(uid, []))
        return result

    def calculate_metrics(member_ids, profile):
        """Calculate one KPI bundle for one or more PM users."""
        member_ids = [uid for uid in member_ids if uid in users_by_id]
        activity_rows = member_rows(activity_per, member_ids)
        closed_rows = member_rows(closed_per, member_ids)
        revenue_rows = member_rows(revenue_per, member_ids)
        ticket_detail_rows = member_rows(ticket_detail_per, member_ids)
        ticket_rows = []
        for uid in member_ids:
            ticket_rows.extend(tickets_per.get(uid, []))

        # ---------------------------------------------------------------
        # PROJECTS: credited when the jobcard is CLOSED in this period.
        # ---------------------------------------------------------------
        achieved = sum((row['projects'] for row in closed_rows), D(0))

        # ---------------------------------------------------------------
        # TARGET / CAPACITY: based on work that overlapped this period.
        # ---------------------------------------------------------------
        target = D(0)
        available_minutes = D(0)
        utilized_minutes = D(0)
        workload_projects = D(0)
        member_capacity_details = []

        for uid in member_ids:
            user_rows = activity_per.get(uid, [])
            member_available = D(days * 8 * 60)
            member_utilized = sum(
                (dec(row.get('minutes')) for row in user_rows), D(0)
            )
            member_workload_projects = sum(
                (dec(row.get('projects')) for row in user_rows), D(0)
            )
            member_average_minutes = (
                member_utilized / member_workload_projects
                if member_workload_projects > 0 else D(0)
            )
            member_target = (
                member_available / member_average_minutes
                if member_average_minutes > 0 else D(0)
            )

            target += member_target
            available_minutes += member_available
            utilized_minutes += member_utilized
            workload_projects += member_workload_projects
            member_capacity_details.append({
                'user_id': uid,
                'available_minutes': q(member_available),
                'utilized_minutes': q(member_utilized),
                'workload_projects': q(member_workload_projects),
                'average_minutes_per_project': q(member_average_minutes),
                'projects_target': q(member_target),
                'has_workload_mix': member_workload_projects > 0,
            })

        has_workload_mix = workload_projects > 0
        average_minutes_per_project = (
            utilized_minutes / workload_projects
            if workload_projects > 0 else D(0)
        )
        remaining_minutes = max(available_minutes - utilized_minutes, D(0))
        over_capacity_minutes = max(utilized_minutes - available_minutes, D(0))
        utilization_pct = pct(utilized_minutes, available_minutes)
        project_pct = (
            min(pct(achieved, target), HUNDRED)
            if target > 0 and has_workload_mix else D(0)
        )

        # Build per-jobcard workload/line-item details from every relevant
        # population, de-duplicating the same service row across populations.
        detail_rows = []
        seen_service_ids = set()
        for row in activity_rows + closed_rows + revenue_rows + ticket_detail_rows:
            sid = row['service'].id
            if sid in seen_service_ids:
                continue
            seen_service_ids.add(sid)
            detail_rows.append(row)

        all_jobcards = {}
        for row in detail_rows:
            all_jobcards[row['jobcard'].id] = row['jobcard']
        for ticket in ticket_rows:
            if ticket.jobcard:
                all_jobcards[ticket.jobcard.id] = ticket.jobcard

        activity_jobcard_ids = {row['jobcard'].id for row in activity_rows}
        closed_jobcard_ids = {row['jobcard'].id for row in closed_rows}

        services_by_jobcard = defaultdict(set)
        quantity_by_jobcard = defaultdict(lambda: D(0))
        projects_by_jobcard = defaultdict(lambda: D(0))
        minutes_by_jobcard = defaultdict(lambda: D(0))
        credited_projects_by_jobcard = defaultdict(lambda: D(0))
        ontime_by_jobcard = defaultdict(lambda: D(0))

        for row in detail_rows:
            jid = row['jobcard'].id
            services_by_jobcard[jid].add(row['service'].service_name or 'Unspecified')
            quantity_by_jobcard[jid] += row['quantity']
            projects_by_jobcard[jid] += row['projects']
            minutes_by_jobcard[jid] += row['minutes']

        for row in closed_rows:
            jid = row['jobcard'].id
            credited_projects_by_jobcard[jid] += row['projects']
            if row['on_time']:
                ontime_by_jobcard[jid] += row['projects']

        # ---------------------------------------------------------------
        # REVENUE: credited in the source transaction month.
        # ---------------------------------------------------------------
        revenue = D(0)
        revenue_by_jobcard = {}
        source_by_jobcard = {}
        revenue_date_by_jobcard = {}
        revenue_jobcard_ids = set()
        for row in revenue_rows:
            jobcard = row['jobcard']
            if jobcard.id in revenue_jobcard_ids:
                continue
            amount, source, event_date = _jobcard_revenue_event(jobcard)
            if not _date_in_period(event_date, start_date, end_date):
                continue
            revenue_jobcard_ids.add(jobcard.id)
            revenue += amount
            revenue_by_jobcard[jobcard.id] = q(amount)
            source_by_jobcard[jobcard.id] = source
            revenue_date_by_jobcard[jobcard.id] = event_date
            all_jobcards[jobcard.id] = jobcard

        revenue_target = sum(
            (
                dec(users_by_id[uid].monthly_ctc) * profile['revenue_multiplier']
                for uid in member_ids
            ), D(0)
        )
        revenue_pct = min(pct(revenue, revenue_target), HUNDRED)

        # ---------------------------------------------------------------
        # MARGIN: only closed-in-period jobcards.
        # ---------------------------------------------------------------
        margin_weighted_value = D(0)
        margin_weight_total = D(0)
        margin_by_jobcard = {}
        margin_source_by_jobcard = {}
        margin_value_by_jobcard = {}
        margin_cost_by_jobcard = {}
        closed_unique = {}
        for row in closed_rows:
            closed_unique[row['jobcard'].id] = row['jobcard']

        for jobcard in closed_unique.values():
            margin_details = _jobcard_margin_details(jobcard)
            margin = margin_details['margin_pct']
            margin_by_jobcard[jobcard.id] = q(margin) if margin is not None else None
            margin_source_by_jobcard[jobcard.id] = margin_details['source']
            margin_value_by_jobcard[jobcard.id] = margin_details['commercial_value_inr']
            margin_cost_by_jobcard[jobcard.id] = margin_details['vendor_cost_inr']
            commercial_weight = dec(margin_details['commercial_value_inr'])
            if margin is not None and commercial_weight > 0:
                margin_weighted_value += dec(margin) * commercial_weight
                margin_weight_total += commercial_weight

        avg_margin = (
            q(margin_weighted_value / margin_weight_total)
            if margin_weight_total > 0 else D(0)
        )
        margin_score_pct = min(pct(avg_margin, profile['margin_target']), HUNDRED)

        # ---------------------------------------------------------------
        # ON-TIME: jobcard closed date vs client deadline, closed this period.
        # ---------------------------------------------------------------
        ontime_eligible = sum(
            (row['projects'] for row in closed_rows if row.get('on_time_eligible')),
            D(0),
        )
        ontime = sum((row['projects'] for row in closed_rows if row['on_time']), D(0))
        ontime_actual = pct(ontime, ontime_eligible)
        ontime_score_pct = min(pct(ontime_actual, profile['on_time_target']), HUNDRED)

        # ---------------------------------------------------------------
        # REWORK: only tickets RAISED in this period.
        # ---------------------------------------------------------------
        tickets_by_jobcard = defaultdict(list)
        for ticket in ticket_rows:
            tickets_by_jobcard[ticket.jobcard_id].append(ticket)
            if ticket.jobcard:
                all_jobcards[ticket.jobcard.id] = ticket.jobcard

        tickets = len(ticket_rows)
        rework_base_jobcard_ids = set(activity_jobcard_ids) | set(tickets_by_jobcard)
        rework_pct = pct(tickets, len(rework_base_jobcard_ids))
        if tickets == 0 or rework_pct <= profile['rework_limit']:
            rework_score_pct = HUNDRED
        else:
            rework_score_pct = max(
                HUNDRED - (rework_pct - profile['rework_limit']) * D(10), D(0)
            )

        weights = profile['weights']
        project_weighted_score = q(project_pct * weights['projects'] / 100)
        revenue_weighted_score = q(revenue_pct * weights['revenue'] / 100)
        margin_weighted_score = q(margin_score_pct * weights['margin'] / 100)
        ontime_weighted_score = q(ontime_score_pct * weights['on_time'] / 100)
        rework_weighted_score = q(rework_score_pct * weights['rework'] / 100)
        gross = q(
            project_weighted_score + revenue_weighted_score
            + margin_weighted_score + ontime_weighted_score
            + rework_weighted_score
        )
        deduction = (
            profile['deduction2'] if tickets >= profile['ticket2']
            else profile['deduction1'] if tickets >= profile['ticket1']
            else D(0)
        )
        score = max(gross - deduction, D(0))

        # ---------------------------------------------------------------
        # Audit-friendly jobcard details / period treatment.
        # ---------------------------------------------------------------
        rows_by_jobcard = defaultdict(list)
        for row in detail_rows:
            rows_by_jobcard[row['jobcard'].id].append(row)

        jobcard_details = []
        period_opened = 0
        period_carried_forward = 0
        period_closed = 0

        for jobcard_id, jobcard in all_jobcards.items():
            job_rows = rows_by_jobcard.get(jobcard_id, [])
            created_date = _as_date(jobcard.created_at)
            closed_date_value = _as_date(jobcard.closed_at)
            created_in_period = _date_in_period(created_date, start_date, end_date)
            closed_in_period = jobcard_id in closed_jobcard_ids
            carried_forward = bool(
                created_date and created_date < start_date
                and (not closed_date_value or closed_date_value >= start_date)
            )
            open_at_period_end = bool(
                created_date and created_date <= end_date
                and (not closed_date_value or closed_date_value > end_date)
            )

            if created_in_period:
                period_opened += 1
            if carried_forward:
                period_carried_forward += 1
            if closed_in_period:
                period_closed += 1

            if carried_forward and closed_in_period:
                period_treatment = 'Carried Forward → Closed in Period'
            elif carried_forward and open_at_period_end:
                period_treatment = 'Carried Forward / In Progress'
            elif created_in_period and closed_in_period:
                period_treatment = 'Opened & Closed in Period'
            elif created_in_period and open_at_period_end:
                period_treatment = 'Opened / In Progress'
            elif jobcard_id in revenue_jobcard_ids:
                period_treatment = 'Billing Event in Period'
            elif tickets_by_jobcard.get(jobcard_id):
                period_treatment = 'Rework Event in Period'
            else:
                period_treatment = 'Period Activity'

            credits = []
            if closed_in_period:
                credits.extend(['Projects', 'Margin', 'On-time'])
            if jobcard_id in revenue_jobcard_ids:
                credits.append('Revenue')
            if tickets_by_jobcard.get(jobcard_id):
                credits.append('Rework')

            line_item_details = []
            for row in job_rows:
                svc = row['service']
                line_item_details.append({
                    'service': svc.service_name or 'Unspecified',
                    'line_item': (
                        svc.quote_item.item_name
                        if svc.quote_item and svc.quote_item.item_name
                        else 'Line item #{0}'.format(svc.id)
                    ),
                    'quantity': q(row['quantity']),
                    'quantity_per_project': (
                        q(row['quantity_per_project'])
                        if row.get('quantity_per_project') is not None else None
                    ),
                    'projects': q(row['projects']),
                    'minutes_per_project': q(row['minutes_per_project']),
                    'effort_minutes': q(row['minutes']),
                    'calculation_rule': row['calculation_rule'],
                })

            # If this is not a revenue-period job, show the current source only
            # as informational status; it contributes zero to this period.
            current_amount, current_source, current_revenue_date = _jobcard_revenue_event(jobcard)
            period_revenue = revenue_by_jobcard.get(jobcard_id, D(0))
            period_revenue_source = source_by_jobcard.get(jobcard_id, 'Not in selected period')
            period_revenue_date = revenue_date_by_jobcard.get(jobcard_id)

            client_deadline = jobcard.client_deadline or (
                jobcard.quote.client_deadline if jobcard.quote else None
            )
            delivery_result = (
                'On time' if closed_in_period and closed_date_value and client_deadline
                and closed_date_value <= _as_date(client_deadline)
                else 'Delayed' if closed_in_period and closed_date_value and client_deadline
                else 'Not eligible'
            )

            ticket_list = tickets_by_jobcard.get(jobcard_id, [])
            jobcard_details.append({
                'id': jobcard.id,
                'code': jobcard.jobcard_code,
                'status': (
                    'Sample Completed' if getattr(jobcard, 'is_sample_job', False)
                    else jobcard.status or '—'
                ),
                'created_at': jobcard.created_at.strftime('%d-%m-%Y') if jobcard.created_at else '—',
                'services': ', '.join(sorted(services_by_jobcard[jobcard_id])) if services_by_jobcard[jobcard_id] else '—',
                'quantity': q(quantity_by_jobcard[jobcard_id]),
                'projects': q(projects_by_jobcard[jobcard_id]),
                'effort_minutes': q(minutes_by_jobcard[jobcard_id]),
                'effort_hours': q(minutes_by_jobcard[jobcard_id] / D(60)),
                'completed_projects': q(credited_projects_by_jobcard[jobcard_id]),
                'on_time_projects': q(ontime_by_jobcard[jobcard_id]),
                'client_deadline': client_deadline.strftime('%d-%m-%Y') if client_deadline else '—',
                'closed_date': jobcard.closed_at.strftime('%d-%m-%Y') if jobcard.closed_at else '—',
                'delivery_result': delivery_result,
                'revenue': q(period_revenue),
                'revenue_source': period_revenue_source,
                'revenue_event_date': (
                    period_revenue_date.strftime('%d-%m-%Y')
                    if period_revenue_date else '—'
                ),
                'current_revenue_source': current_source,
                'current_revenue_event_date': (
                    _as_date(current_revenue_date).strftime('%d-%m-%Y')
                    if _as_date(current_revenue_date) else '—'
                ),
                'margin_pct': margin_by_jobcard.get(jobcard_id),
                'margin_source': margin_source_by_jobcard.get(jobcard_id, 'Not credited in selected period'),
                'commercial_value_inr': margin_value_by_jobcard.get(jobcard_id, D(0)),
                'vendor_cost_inr': margin_cost_by_jobcard.get(jobcard_id, D(0)),
                'line_items': line_item_details,
                'ticket_count': len(ticket_list),
                'ticket_numbers': ', '.join(t.ticket_no for t in ticket_list) if ticket_list else '—',
                'period_treatment': period_treatment,
                'kpi_credits': credits,
                'kpi_credit_label': ', '.join(credits) if credits else 'Workload only / No KPI credit',
                'created_in_period': created_in_period,
                'carried_forward': carried_forward,
                'closed_in_period': closed_in_period,
                'open_at_period_end': open_at_period_end,
                'revenue_in_period': jobcard_id in revenue_jobcard_ids,
                'rework_in_period': bool(ticket_list),
            })

        jobcard_details.sort(
            key=lambda item: (
                0 if item['closed_in_period'] else 1,
                0 if item['carried_forward'] else 1,
                item['code'] or '',
            )
        )

        return {
            'projects_target': q(target),
            'projects_achieved': q(achieved),
            'has_workload_mix': has_workload_mix,
            'workload_mix_message': 'Workload mix available' if has_workload_mix else 'No workload mix available',
            'available_minutes': q(available_minutes),
            'available_hours': q(available_minutes / D(60)),
            'utilized_minutes': q(utilized_minutes),
            'utilized_hours': q(utilized_minutes / D(60)),
            'remaining_minutes': q(remaining_minutes),
            'remaining_hours': q(remaining_minutes / D(60)),
            'over_capacity_minutes': q(over_capacity_minutes),
            'over_capacity_hours': q(over_capacity_minutes / D(60)),
            'utilization_pct': q(utilization_pct),
            'average_minutes_per_project': q(average_minutes_per_project),
            'required_target_formula': (
                '{0} available min / {1} average min per project = {2} required projects'.format(
                    q(available_minutes), q(average_minutes_per_project), q(target)
                ) if has_workload_mix else 'No workload mix available'
            ),
            'workload_projects': q(workload_projects),
            'member_capacity_details': member_capacity_details,
            'projects_weight': q(weights['projects']),
            'revenue_weight': q(weights['revenue']),
            'margin_weight': q(weights['margin']),
            'on_time_weight': q(weights['on_time']),
            'rework_weight': q(weights['rework']),
            'projects_pct': q(project_pct),
            'projects_weighted_score': q(project_weighted_score),
            'revenue': q(revenue),
            'revenue_target': q(revenue_target),
            'revenue_pct': q(revenue_pct),
            'revenue_weighted_score': q(revenue_weighted_score),
            'margin_pct': q(avg_margin),
            'margin_score_pct': q(margin_score_pct),
            'margin_weighted_score': q(margin_weighted_score),
            'on_time_pct': q(ontime_actual),
            'on_time_score_pct': q(ontime_score_pct),
            'on_time_weighted_score': q(ontime_weighted_score),
            'rework_pct': q(rework_pct),
            'rework_score_pct': q(rework_score_pct),
            'rework_weighted_score': q(rework_weighted_score),
            'tickets': tickets,
            'gross_score': q(gross),
            'ticket_deduction': q(deduction),
            'individual_score': q(score),
            'jobcards': jobcard_details,
            'jobcard_count': len(jobcard_details),
            'opened_in_period': period_opened,
            'carried_forward': period_carried_forward,
            'closed_in_period': period_closed,
            'revenue_events_in_period': len(revenue_jobcard_ids),
            'rework_jobcards_in_period': len(tickets_by_jobcard),
        }

    individual = {}
    for user in users:
        profile = _profile_data(_profile_for(user))
        metrics = calculate_metrics([user.id], profile)
        metrics['user'] = user
        metrics['profile'] = profile
        individual[user.id] = metrics

    rows = []
    for uid, own_data in individual.items():
        profile = own_data['profile']
        team_ids = [
            team_id
            for team_id in pm_team_user_ids(uid, profile['include_indirect'])
            if team_id in users_by_id
        ]
        is_tl = bool(team_ids)
        team_metrics = calculate_metrics(team_ids, profile) if is_tl else None
        team_score = team_metrics['individual_score'] if team_metrics else None
        final_score = (
            q(
                own_data['individual_score'] * profile['tl_individual'] / 100
                + team_score * profile['tl_team'] / 100
            ) if is_tl else own_data['individual_score']
        )

        display_data = team_metrics if is_tl else own_data
        user = own_data['user']
        team_member_details = []
        for team_id in team_ids:
            team_user = users_by_id.get(team_id)
            if not team_user:
                continue
            team_member_details.append({
                'id': team_user.id,
                'name': team_user.name,
                'email': team_user.email,
                'designation': (
                    team_user.profile.designation.name
                    if team_user.profile and team_user.profile.designation else None
                ),
                'department': team_user.profile.department if team_user.profile else None,
                'score': individual[team_id]['individual_score'] if team_id in individual else D('0'),
                'jobcards': individual[team_id]['jobcard_count'] if team_id in individual else 0,
            })
        team_member_details.sort(key=lambda item: item['name'] or '')

        row = {key: value for key, value in display_data.items() if key not in {'user', 'profile'}}
        row.update({
            'id': uid,
            'name': user.name,
            'email': user.email,
            'department': user.profile.department if user.profile else None,
            'designation': (
                user.profile.designation.name
                if user.profile and user.profile.designation else None
            ),
            'profile_name': profile['name'],
            'is_tl': is_tl,
            'team_members': len(team_ids),
            'team_member_details': team_member_details,
            'team_score': team_score,
            'own_score': own_data['individual_score'],
            'own_jobcards': own_data['jobcards'],
            'tl_individual_weight': profile['tl_individual'],
            'tl_team_weight': profile['tl_team'],
            'final_score': final_score,
        })
        rows.append(row)

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

    return {
        'totals': {
            'employees': len(rows),
            'average_score': (
                q(sum((row['final_score'] for row in rows), D(0)) / len(rows))
                if rows else D(0)
            ),
            'top_score': rows[0]['final_score'] if rows else D(0),
            'above_90': sum(row['final_score'] >= 90 for row in rows),
            'below_60': sum(row['final_score'] < 60 for row in rows),
        },
        'rows': rows,
        'working_days': days,
        'period_logic': {
            'workload': 'Jobcards active during the selected period',
            'projects': 'Jobcard closed date',
            'margin': 'Jobcard closed date',
            'on_time': 'Jobcard closed date vs client deadline',
            'revenue': 'Invoice / PI / Ready-for-Billing transaction date',
            'rework': 'Rework ticket raised date',
        },
    }
