from datetime import date, datetime, timedelta
from decimal import Decimal

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app
from flask_login import login_required, current_user
from sqlalchemy import func, or_, create_engine, text

from .. import db
from ..utils import require_perm
from ..models import (
    User,
    Designation,
    EmployeeProfile,
    KpiMaster,
    KpiAssignment,
    Quote,
    Opportunity,
    Invoice,
    InvoicePayment,
    LeadActivity,
    ActivityType,
    Project,
    OperationsJobcard,
    OperationsJobcardAssignment,
    CurrencyRateMaster,
)

kpi_bp = Blueprint("kpi_master", __name__, template_folder="../templates")


# -------------------------------------------------------
# Helpers
# -------------------------------------------------------

def _kpi_client_amount_from_jobcard(jobcard):
    invoice = (
        Invoice.query
        .filter(Invoice.quote_id == jobcard.quote_id)
        .filter(Invoice.status != "Cancelled")
        .order_by(Invoice.id.desc())
        .first()
    )

    if not invoice:
        return Decimal("0")

    amount = _to_decimal(invoice.subtotal) - _to_decimal(invoice.discount)

    if amount <= 0:
        amount = (
            _to_decimal(invoice.total_amount)
            - _to_decimal(invoice.cgst)
            - _to_decimal(invoice.sgst)
            - _to_decimal(invoice.igst)
            - _to_decimal(invoice.tax)
        )

    if amount <= 0:
        return Decimal("0")

    currency = (invoice.currency or "INR").strip().upper()
    rate = _get_rate_to_inr(currency, invoice.invoice_date)

    return amount * rate


def _kpi_vendor_amount_from_jobcard(jobcard):
    total = Decimal("0")

    for svc in jobcard.services.all():
        assignments = svc.assignments.filter(
            OperationsJobcardAssignment.assigned_to_type == "VENDOR",
            OperationsJobcardAssignment.status != "Cancelled",
            OperationsJobcardAssignment.replaced_at.is_(None),
            OperationsJobcardAssignment.parent_assignment_id.is_(None),
        ).all()

        if assignments:
            for a in assignments:
                qty = _to_decimal(a.assigned_qty)
                rate = _to_decimal(a.rate)

                if a.flat_rate:
                    total += rate
                else:
                    total += qty * rate
        else:
            if svc.vendor_id or svc.vendor_name:
                qty = _to_decimal(getattr(svc, "vendor_wordcount", 0))
                rate = _to_decimal(getattr(svc, "vendor_rate", 0))

                if getattr(svc, "vendor_flat_rate", False):
                    total += rate
                else:
                    total += qty * rate

    return total


def _get_assignment_target_rows(assignment_type: str, designation_id=None, user_id=None):
    qs = (
        KpiAssignment.query
        .join(KpiMaster, KpiMaster.id == KpiAssignment.kpi_id)
        .filter(KpiAssignment.assignment_type == assignment_type)
    )

    if assignment_type == "designation":
        qs = qs.filter(KpiAssignment.designation_id == designation_id)
    else:
        qs = qs.filter(KpiAssignment.user_id == user_id)

    return qs.order_by(KpiMaster.sort_order.asc(), KpiMaster.name.asc(), KpiAssignment.id.asc()).all()

def fetch_bill_date_from_lms(jobcard_no):
    if not jobcard_no:
        return None

    try:
        engine = get_external_engine()

        sql = text("""
            SELECT TOP 1
                BillDate
            FROM dbo.TranslationBill
            WHERE JobCardNo = :jobcard_no
            ORDER BY BillDate DESC
        """)

        with engine.begin() as conn:
            row = conn.execute(sql, {
                "jobcard_no": str(jobcard_no).strip()
            }).mappings().first()

        if not row or not row.get("BillDate"):
            return None

        bill_date = row.get("BillDate")

        if isinstance(bill_date, datetime):
            return bill_date.date()

        return bill_date

    except Exception:
        return None

def get_external_engine():
    external_uri = current_app.config.get("LMS_DB_URI")
    if not external_uri:
        raise Exception("LMS_DB_URI is not configured in config.")

    return create_engine(external_uri, pool_pre_ping=True)

def _group_assignments_for_view(assignments):
    grouped = []

    bucket = {}
    for a in assignments:
        if a.assignment_type == "user":
            group_key = f"user_{a.user_id or 0}"
            group_label = f"User: {a.user.name if a.user else 'Unknown'}"
            group_sub = a.user.email if a.user and a.user.email else ""
        else:
            group_key = f"designation_{a.designation_id or 0}"
            group_label = f"Designation: {a.designation.name if a.designation else 'Unknown'}"
            group_sub = ""

        if group_key not in bucket:
            bucket[group_key] = {
                "key": group_key,
                "label": group_label,
                "sub_label": group_sub,
                "assignment_type": a.assignment_type,
                "rows": [],
                "active_weightage": Decimal("0"),
            }

        bucket[group_key]["rows"].append(a)
        if a.is_active:
            bucket[group_key]["active_weightage"] += _to_decimal(a.weightage)

    grouped = list(bucket.values())
    grouped.sort(key=lambda x: x["label"].lower())
    return grouped

def _clean(v):
    return (v or "").strip()


def _to_decimal(v, default="0"):
    try:
        s = str(v or "").strip().replace(",", "")
        if not s:
            return Decimal(default)
        return Decimal(s)
    except Exception:
        return Decimal(default)


def _parse_date(v):
    v = (v or "").strip()
    if not v:
        return None
    try:
        return datetime.strptime(v, "%Y-%m-%d").date()
    except Exception:
        return None


def _validate_total_weightage(kpi_assignment, new_weightage):
    qs = KpiAssignment.query.filter(
        KpiAssignment.is_active == True,
        KpiAssignment.assignment_type == kpi_assignment["assignment_type"]
    )

    if kpi_assignment["assignment_type"] == "user":
        qs = qs.filter(KpiAssignment.user_id == kpi_assignment["user_id"])
    else:
        qs = qs.filter(KpiAssignment.designation_id == kpi_assignment["designation_id"])

    if kpi_assignment.get("exclude_id"):
        qs = qs.filter(KpiAssignment.id != kpi_assignment["exclude_id"])

    total_existing = qs.with_entities(
        func.coalesce(func.sum(KpiAssignment.weightage), 0)
    ).scalar() or 0
    total_existing = _to_decimal(total_existing)

    if total_existing + new_weightage > Decimal("100"):
        return False, total_existing

    return True, total_existing


def _team_user_ids(manager_user_id: int, include_self: bool = True):
    seen = set([manager_user_id]) if include_self else set()
    stack = [manager_user_id]

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

    return list(seen)


def _allowed_dashboard_user_ids():
    if current_user.has_perm("kpi.view_all"):
        return None
    if current_user.has_perm("kpi.view_team"):
        return _team_user_ids(current_user.id, include_self=True)
    return [current_user.id]


def _month_bounds(year: int, month: int):
    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 _quarter_bounds(year: int, quarter: int):
    quarter = max(1, min(4, int(quarter or 1)))
    start_month = ((quarter - 1) * 3) + 1
    start = date(year, start_month, 1)

    if quarter == 4:
        end = date(year + 1, 1, 1)
    else:
        end = date(year, start_month + 3, 1)

    return start, end


def _year_bounds(year: int):
    return date(year, 1, 1), date(year + 1, 1, 1)


def _period_bounds(period_type: str, year: int, month: int = None, quarter: int = None):
    if period_type == "quarterly":
        return _quarter_bounds(year, quarter or 1)
    if period_type == "yearly":
        return _year_bounds(year)
    return _month_bounds(year, month or 1)


def _assignment_in_period(assignment: KpiAssignment, start_date: date, end_date: date):
    if assignment.effective_from and assignment.effective_from >= end_date:
        return False
    if assignment.effective_to and assignment.effective_to < start_date:
        return False
    return True


def _target_for_period(assignment: KpiAssignment, period_type: str):
    if period_type == "yearly":
        return _to_decimal(assignment.yearly_target)
    if period_type == "quarterly":
        return _to_decimal(assignment.quarterly_target)
    return _to_decimal(assignment.monthly_target)


def _get_activity_type_ids_by_keywords(keywords):
    rows = ActivityType.query.filter(ActivityType.is_active == True).all()
    ids = []
    for row in rows:
        nm = (row.name or "").strip().lower()
        if any(k in nm for k in keywords):
            ids.append(row.id)
    return ids


def _get_assignments_for_user(user: User, start_date: date, end_date: date):
    """
    Returns assignments applicable to the user for the selected period.
    User-wise assignments override designation-wise assignments for the same KPI.
    """
    user_designation_id = None
    if getattr(user, "profile", None):
        user_designation_id = user.profile.designation_id

    all_rows = (
        KpiAssignment.query
        .join(KpiMaster, KpiMaster.id == KpiAssignment.kpi_id)
        .filter(KpiAssignment.is_active == True)
        .filter(KpiMaster.is_active == True)
        .filter(
            or_(
                KpiAssignment.user_id == user.id,
                KpiAssignment.designation_id == user_designation_id
            )
        )
        .order_by(KpiMaster.sort_order.asc(), KpiMaster.name.asc(), KpiAssignment.id.asc())
        .all()
    )

    applicable = [row for row in all_rows if _assignment_in_period(row, start_date, end_date)]

    chosen = {}
    for row in applicable:
        key = row.kpi_id
        existing = chosen.get(key)

        if existing is None:
            chosen[key] = row
            continue

        if row.assignment_type == "user" and existing.assignment_type != "user":
            chosen[key] = row

    return list(chosen.values())

def _get_rate_to_inr(currency_code, ref_date):
    currency_code = (currency_code or "INR").strip().upper()
    currency_code = {"EURO": "EUR", "EUROS": "EUR", "€": "EUR"}.get(currency_code, currency_code)

    if currency_code == "INR":
        return Decimal("1")

    if not ref_date:
        ref_date = date.today()

    rate_row = (
        CurrencyRateMaster.query
        .filter(CurrencyRateMaster.currency_code == currency_code)
        .filter(CurrencyRateMaster.year == ref_date.year)
        .filter(CurrencyRateMaster.month == ref_date.month)
        .first()
    )

    if not rate_row:
        rate_row = (
            CurrencyRateMaster.query
            .filter(CurrencyRateMaster.currency_code == currency_code)
            .order_by(
                CurrencyRateMaster.year.desc(),
                CurrencyRateMaster.month.desc()
            )
            .first()
        )

    if not rate_row:
        return Decimal("0")

    return _to_decimal(rate_row.rate_to_inr, "0")

def _quote_amount_without_tax(q):
    if not q:
        return Decimal("0")

    subtotal = _to_decimal(getattr(q, "subtotal", 0))
    discount = _to_decimal(getattr(q, "discount", 0))

    amount = subtotal - discount
    return amount if amount > 0 else Decimal("0")

def _latest_selected_quote_for_quote(base_quote):
    """
    Returns latest confirmed quote version for the same opportunity.

    Project.quote_id may point to the originally assigned quote.
    KPI should calculate value from the latest confirmed quote version.
    """
    if not base_quote:
        return None

    opportunity_id = getattr(base_quote, "opportunity_id", None)

    if not opportunity_id:
        return base_quote

    latest_quote = (
        Quote.query
        .filter(Quote.opportunity_id == opportunity_id)
        .filter(Quote.proposal_confirmed_at.isnot(None))
        .order_by(
            Quote.version.desc(),
            Quote.id.desc()
        )
        .first()
    )

    if latest_quote:
        return latest_quote

    # Fallback: if no confirmed quote found, use latest version available.
    latest_quote = (
        Quote.query
        .filter(Quote.opportunity_id == opportunity_id)
        .order_by(
            Quote.version.desc(),
            Quote.id.desc()
        )
        .first()
    )

    return latest_quote or base_quote

def _money_json(v):
    return float(round(_to_decimal(v), 2))


def _get_kpi_calculation_details(kpi_code: str, user_ids, start_date: date, end_date: date):
    code = (kpi_code or "").strip().lower()
    user_ids = user_ids or []

    result = {
        "cn_rows": [],
        "pms_rows": [],
        "cn_total": Decimal("0"),
        "pms_total": Decimal("0"),
        "grand_total": Decimal("0"),
    }

    if not user_ids:
        return result

    # Crystal Nexus invoices
    if code in ("total_sales","sales","sales_kpi","cn_invoice_value_inr","crystal_nexus_invoice_value_inr","confirmed_billed_jobcard_value_inr","billed_jobcard_value_inr","confirmed_billed_quotation_value_inr",):
        cn_rows = (
            db.session.query(Invoice)
            .join(Quote, Quote.id == Invoice.quote_id)
            .join(Opportunity, Opportunity.id == Quote.opportunity_id)
            .filter(or_(
                Quote.created_by_id.in_(user_ids),
                Opportunity.owner_id.in_(user_ids)
            ))
            .filter(Invoice.status != "Cancelled")
            .filter(Invoice.invoice_date >= start_date)
            .filter(Invoice.invoice_date < end_date)
            .all()
        )

        for inv in cn_rows:
            taxable = _to_decimal(inv.subtotal) - _to_decimal(inv.discount)
            if taxable < 0:
                taxable = Decimal("0")

            invoice_date = inv.invoice_date or start_date
            currency_code = (inv.currency or "INR").strip().upper()
            rate_to_inr = _get_rate_to_inr(currency_code, invoice_date)
            inr_value = taxable * rate_to_inr

            result["cn_total"] += inr_value

            jobcard_no = ""

            if inv.jobcard:
                jobcard_no = inv.jobcard.jobcard_code or ""
            elif inv.project and inv.project.jobcard_no:
                jobcard_no = inv.project.jobcard_no or ""

            result["cn_rows"].append({
                "invoice_no": inv.invoice_no,
                "jobcard_no": jobcard_no,
                "invoice_date": invoice_date.strftime("%d-%m-%Y") if invoice_date else "",
                "client": inv.client.company_name if inv.client else "",
                "user_name": (
                    inv.quote.created_by.name
                    if inv.quote and inv.quote.created_by
                    else (
                        inv.quote.opportunity.owner.name
                        if inv.quote and inv.quote.opportunity and inv.quote.opportunity.owner
                        else ""
                    )
                ),
                "currency": currency_code,
                "taxable": _money_json(taxable),
                "rate": _money_json(rate_to_inr),
                "inr_value": _money_json(inr_value),
            })

    # PMS billed jobcards
    user_filter_conditions = [
        Quote.created_by_id.in_(user_ids),
        Opportunity.owner_id.in_(user_ids),
        Project.created_by_id.in_(user_ids),
    ]

    if hasattr(Quote, "assigned_to_id"):
        user_filter_conditions.append(Quote.assigned_to_id.in_(user_ids))

    pms_rows = (
        db.session.query(Project, Quote)
        .join(Quote, Quote.id == Project.quote_id)
        .outerjoin(Opportunity, Opportunity.id == Quote.opportunity_id)
        .filter(or_(*user_filter_conditions))
        .filter(Project.jobcard_no.isnot(None))
        .filter(Project.jobcard_no != "")
        .filter(Project.pms_bill_date.isnot(None))
        .filter(func.lower(func.trim(Project.jobcard_status)) == "billed")
        .all()
    )

    for project, quote in pms_rows:
        bill_date = project.pms_bill_date
        if isinstance(bill_date, datetime):
            bill_date = bill_date.date()

        if not bill_date or bill_date < start_date or bill_date >= end_date:
            continue

        latest_quote = _latest_selected_quote_for_quote(quote)

        taxable = _quote_amount_without_tax(latest_quote)
        if taxable <= 0:
            taxable = _quote_amount_without_tax(quote)
        if taxable <= 0:
            taxable = _to_decimal(project.contract_value or 0)

        currency_code = (
            getattr(latest_quote, "currency", None)
            or getattr(quote, "currency", None)
            or project.currency
            or "INR"
        ).strip().upper()

        rate_to_inr = _get_rate_to_inr(currency_code, bill_date)
        inr_value = taxable * rate_to_inr

        result["pms_total"] += inr_value

        result["pms_rows"].append({
            "jobcard_no": project.jobcard_no or "",
            "bill_no": project.pms_bill_no or "",
            "bill_date": bill_date.strftime("%d-%m-%Y"),
            "project": project.name or "",
            "quote_code": latest_quote.quote_code if latest_quote else quote.quote_code,
            "currency": currency_code,
            "taxable": _money_json(taxable),
            "rate": _money_json(rate_to_inr),
            "inr_value": _money_json(inr_value),
        })

    result["grand_total"] = result["cn_total"] + result["pms_total"]
    return result

def _invoice_user_filter_conditions(user_ids):
    conditions = [
        Quote.created_by_id.in_(user_ids),
        Opportunity.owner_id.in_(user_ids),
    ]

    if hasattr(Quote, "assigned_to_id"):
        conditions.append(Quote.assigned_to_id.in_(user_ids))

    return conditions

def _calculate_kpi_actual(kpi_code: str, user_ids, start_date: date, end_date: date):
    """
    end_date is exclusive
    """
    code = (kpi_code or "").strip().lower()
    user_ids = user_ids or []

    if not user_ids:
        return Decimal("0")

    if code in (
        "total_sales",
        "sales",
        "sales_kpi",
        "cn_invoice_value_inr",
        "crystal_nexus_invoice_value_inr",
        "confirmed_billed_jobcard_value_inr",
        "billed_jobcard_value_inr",
        "confirmed_billed_quotation_value_inr",
    ):

        details = _get_kpi_calculation_details(
            kpi_code=code,
            user_ids=user_ids,
            start_date=start_date,
            end_date=end_date
        )
        return details["grand_total"]

    if code in ("total_collections", "collections", "collections_kpi"):
        amount = (
            db.session.query(func.coalesce(func.sum(InvoicePayment.amount), 0))
            .join(Invoice, Invoice.id == InvoicePayment.invoice_id)
            .join(Quote, Quote.id == Invoice.quote_id)
            .outerjoin(Opportunity, Opportunity.id == Quote.opportunity_id)
            .filter(or_(*_invoice_user_filter_conditions(user_ids)))
            .filter(Invoice.status != "Cancelled")
            .filter(InvoicePayment.status == "Verified")
            .filter(InvoicePayment.payment_date >= start_date)
            .filter(InvoicePayment.payment_date < end_date)
            .scalar()
        ) or 0

        return _to_decimal(amount)
        
    if code in ("collections_within_60_days", "collections_60_days", "collection_within_60_days"):
        invoices = (
            Invoice.query
            .join(Quote, Quote.id == Invoice.quote_id)
            .outerjoin(Opportunity, Opportunity.id == Quote.opportunity_id)
            .filter(or_(*_invoice_user_filter_conditions(user_ids)))
            .filter(Invoice.status != "Cancelled")
            .filter(Invoice.invoice_date >= start_date)
            .filter(Invoice.invoice_date < end_date)
            .all()
        )

        actual_collection = Decimal("0")

        for inv in invoices:
            invoice_date = inv.invoice_date
            if not invoice_date:
                continue

            collection_deadline = invoice_date + timedelta(days=60)

            paid_amount = (
                db.session.query(func.coalesce(func.sum(InvoicePayment.amount), 0))
                .filter(InvoicePayment.invoice_id == inv.id)
                .filter(InvoicePayment.status == "Verified")
                .filter(InvoicePayment.payment_date >= invoice_date)
                .filter(InvoicePayment.payment_date <= collection_deadline)
                .scalar()
            ) or 0

            actual_collection += _to_decimal(paid_amount)

        return actual_collection

    if code in ("total_calls", "calls", "call_count"):
        call_type_ids = _get_activity_type_ids_by_keywords(["call", "phone"])
        if not call_type_ids:
            return Decimal("0")

        count = (
            db.session.query(func.count(LeadActivity.id))
            .filter(LeadActivity.created_by_id.in_(user_ids))
            .filter(LeadActivity.activity_type_id.in_(call_type_ids))
            .filter(LeadActivity.activity_at >= datetime.combine(start_date, datetime.min.time()))
            .filter(LeadActivity.activity_at < datetime.combine(end_date, datetime.min.time()))
            .scalar()
        ) or 0
        return Decimal(str(count))

    if code in ("total_meetings", "meetings", "meeting_count"):
        meeting_type_ids = _get_activity_type_ids_by_keywords(["meeting", "demo"])
        if not meeting_type_ids:
            return Decimal("0")

        count = (
            db.session.query(func.count(LeadActivity.id))
            .filter(LeadActivity.created_by_id.in_(user_ids))
            .filter(LeadActivity.activity_type_id.in_(meeting_type_ids))
            .filter(LeadActivity.activity_at >= datetime.combine(start_date, datetime.min.time()))
            .filter(LeadActivity.activity_at < datetime.combine(end_date, datetime.min.time()))
            .scalar()
        ) or 0
        return Decimal(str(count))

    if code in ("total_leads_converted", "leads_converted", "lead_converted"):
        count = (
            db.session.query(func.count(Opportunity.id))
            .filter(Opportunity.owner_id.in_(user_ids))
            .filter(Opportunity.lead_id.isnot(None))
            .filter(Opportunity.created_at >= datetime.combine(start_date, datetime.min.time()))
            .filter(Opportunity.created_at < datetime.combine(end_date, datetime.min.time()))
            .scalar()
        ) or 0
        return Decimal(str(count))

    if code in ("average_profit_margin", "avg_profit_margin", "profit_margin"):

        user_filter_conditions = [
            Quote.created_by_id.in_(user_ids),
            Opportunity.owner_id.in_(user_ids),
        ]

        if hasattr(Quote, "assigned_to_id"):
            user_filter_conditions.append(Quote.assigned_to_id.in_(user_ids))

        rows = (
            db.session.query(OperationsJobcard, Invoice)
            .join(Quote, Quote.id == OperationsJobcard.quote_id)
            .outerjoin(Opportunity, Opportunity.id == Quote.opportunity_id)
            .join(Invoice, Invoice.quote_id == Quote.id)
            .filter(or_(*user_filter_conditions))
            .filter(Invoice.status != "Cancelled")
            .filter(Invoice.invoice_date >= start_date)
            .filter(Invoice.invoice_date < end_date)
            .filter(OperationsJobcard.closed_at.isnot(None))
            .all()
        )

        total_client_amount = Decimal("0")
        total_vendor_amount = Decimal("0")
        used_jobcard_ids = set()

        for jc, invoice in rows:
            if jc.id in used_jobcard_ids:
                continue

            used_jobcard_ids.add(jc.id)

            client_amount = _kpi_client_amount_from_jobcard(jc)
            vendor_amount = _kpi_vendor_amount_from_jobcard(jc)

            if client_amount <= 0:
                continue

            total_client_amount += client_amount
            total_vendor_amount += vendor_amount

        if total_client_amount <= 0:
            return Decimal("0")

        return ((total_client_amount - total_vendor_amount) / total_client_amount) * Decimal("100")

    # Unknown / newly-added KPI codes must never break the Sales KPI dashboard.
    # They may belong to another module (for example Operations KPI) or may not
    # yet have a Sales calculation implemented.
    current_app.logger.warning(
        "No Sales KPI actual-calculation handler found for KPI code '%s'. "
        "Returning 0 instead of None.",
        code,
    )
    return Decimal("0")


def _calculate_collection_60_days_target(user_ids, start_date, end_date):
    invoices = (
        Invoice.query
        .join(Quote, Quote.id == Invoice.quote_id)
        .outerjoin(Opportunity, Opportunity.id == Quote.opportunity_id)
        .filter(or_(*_invoice_user_filter_conditions(user_ids)))
        .filter(Invoice.status != "Cancelled")
        .filter(Invoice.invoice_date >= start_date)
        .filter(Invoice.invoice_date < end_date)
        .all()
    )

    total = Decimal("0")

    for inv in invoices:
        taxable = _to_decimal(inv.subtotal) - _to_decimal(inv.discount)

        if taxable <= 0:
            taxable = _to_decimal(inv.total_amount)

        currency = (inv.currency or "INR").strip().upper()
        rate = _get_rate_to_inr(currency, inv.invoice_date)

        total += taxable * rate

    return total

def _build_self_dashboard_rows(user: User, period_type: str, year: int, month: int = None, quarter: int = None):
    start_date, end_date = _period_bounds(period_type, year, month, quarter)
    assignments = _get_assignments_for_user(user, start_date, end_date)

    rows = []

    # Self + reportees for actual calculation
    scope_user_ids = _team_user_ids(user.id, include_self=True)

    for assignment in assignments:
        kpi = assignment.kpi

        # Target should come only from this user's own KPI assignment
        target = _to_decimal(
            _target_for_period(assignment, period_type)
        )

        if (kpi.code or "").strip().lower() in (
            "collections_within_60_days",
            "collections_60_days",
            "collection_within_60_days"
        ):
            target = _calculate_collection_60_days_target(
                user_ids=scope_user_ids,
                start_date=start_date,
                end_date=end_date
            )

        # Actual should include self + reportees
        actual = _to_decimal(
            _calculate_kpi_actual(
                kpi_code=kpi.code,
                user_ids=scope_user_ids,
                start_date=start_date,
                end_date=end_date
            )
        )

        achievement = Decimal("0")
        weighted_score = Decimal("0")
        weightage = _to_decimal(getattr(assignment, "weightage", 0))

        if target > 0:
            achievement = (actual / target) * Decimal("100")
            capped_achievement = min(achievement, Decimal("100"))
            weighted_score = (capped_achievement * weightage) / Decimal("100")

        rows.append({
            "mode": "self",
            "user": user,
            "kpi": kpi,
            "assignment": assignment,
            "target": target,
            "actual": actual,
            "achievement": achievement,
            "start_date": start_date,
            "end_date": end_date,
            "weightage": weightage,
            "weighted_score": weighted_score,
        })

    return rows

def _add_month(year, month, step=1):
    month = month + step
    while month > 12:
        month -= 12
        year += 1
    while month < 1:
        month += 12
        year -= 1
    return year, month


def _month_range(start_year, start_month, end_year, end_month):
    months = []
    y, m = start_year, start_month

    while (y < end_year) or (y == end_year and m <= end_month):
        months.append({
            "year": y,
            "month": m,
            "label": date(y, m, 1).strftime("%b %Y")
        })
        y, m = _add_month(y, m, 1)

    return months


def _total_weighted_score_for_user_month(user, year, month):
    rows = _build_self_dashboard_rows(
        user=user,
        period_type="monthly",
        year=year,
        month=month
    )

    total_score = sum(
        (row.get("weighted_score", Decimal("0")) for row in rows),
        Decimal("0")
    )

    total_weightage = sum(
        (row.get("weightage", Decimal("0")) for row in rows),
        Decimal("0")
    )

    return {
        "score": total_score,
        "weightage": total_weightage,
        "rows": rows
    }

def _build_team_dashboard_rows(manager: User, period_type: str, year: int, month: int = None, quarter: int = None):
    """
    Team KPI:
    - Amount/count KPIs: sum of reportees' targets and actuals
    - Percentage KPIs: average target, calculated actual
    - Collections within 60 days: auto target from invoices
    """
    start_date, end_date = _period_bounds(period_type, year, month, quarter)
    reportee_ids = _team_user_ids(manager.id, include_self=False)

    if not reportee_ids:
        return []

    reportees = User.query.filter(User.id.in_(reportee_ids)).all()

    percentage_kpis = (
        "average_profit_margin",
        "avg_profit_margin",
        "profit_margin",
    )

    auto_target_kpis = (
        "collections_within_60_days",
        "collections_60_days",
        "collection_within_60_days",
    )

    merged = {}

    for reportee in reportees:
        assignments = _get_assignments_for_user(reportee, start_date, end_date)

        for assignment in assignments:
            kpi = assignment.kpi
            code = (kpi.code or "").strip().lower()
            key = kpi.id

            if key not in merged:
                merged[key] = {
                    "mode": "team",
                    "user": manager,
                    "kpi": kpi,
                    "assignment": None,
                    "target": Decimal("0"),
                    "actual": Decimal("0"),
                    "achievement": Decimal("0"),
                    "start_date": start_date,
                    "end_date": end_date,
                    "team_members": [],
                    "target_count": Decimal("0"),
                }

            if reportee.id not in merged[key]["team_members"]:
                merged[key]["team_members"].append(reportee.id)

            target_value = _target_for_period(assignment, period_type)

            # Percentage KPI target should be averaged, not summed
            if code in percentage_kpis:
                merged[key]["target"] += target_value
                merged[key]["target_count"] += Decimal("1")

            # Auto target KPI will be calculated later from invoices
            elif code in auto_target_kpis:
                pass

            # Normal KPI target should be summed
            else:
                merged[key]["target"] += target_value

    for key, row in merged.items():
        code = (row["kpi"].code or "").strip().lower()
        team_user_ids = row["team_members"]

        if code in auto_target_kpis:
            row["target"] = _calculate_collection_60_days_target(
                user_ids=team_user_ids,
                start_date=start_date,
                end_date=end_date
            )

        elif code in percentage_kpis:
            if row["target_count"] > 0:
                row["target"] = row["target"] / row["target_count"]

        row["actual"] = _to_decimal(
            _calculate_kpi_actual(
                kpi_code=row["kpi"].code,
                user_ids=team_user_ids,
                start_date=start_date,
                end_date=end_date
            )
        )

        row["target"] = _to_decimal(row.get("target"))

        if row["target"] > 0:
            row["achievement"] = (row["actual"] / row["target"]) * Decimal("100")

    return sorted(
        merged.values(),
        key=lambda x: ((x["kpi"].sort_order or 0), (x["kpi"].name or "").lower())
    )

# -------------------------------------------------------
# KPI Master
# -------------------------------------------------------
@kpi_bp.route("/kpi/master", methods=["GET", "POST"])
@login_required
@require_perm("kpi.manage")
def kpi_master():
    if request.method == "POST":
        action = request.form.get("action")

        if action == "create":
            name = _clean(request.form.get("name"))
            code = _clean(request.form.get("code")).lower().replace(" ", "_")
            description = _clean(request.form.get("description"))
            source_type = (_clean(request.form.get("source_type")) or "SYSTEM").upper()
            aggregation_type = (_clean(request.form.get("aggregation_type")) or "COUNT").upper()
            unit = _clean(request.form.get("unit"))
            sort_order = int(request.form.get("sort_order") or 1)
            is_active = bool(request.form.get("is_active"))

            if not name or not code:
                flash("Name and code are required.", "danger")
                return redirect(url_for("kpi_master.kpi_master"))

            existing = KpiMaster.query.filter(
                or_(KpiMaster.name == name, KpiMaster.code == code)
            ).first()
            if existing:
                flash("KPI name or code already exists.", "warning")
                return redirect(url_for("kpi_master.kpi_master"))

            row = KpiMaster(
                name=name,
                code=code,
                description=description or None,
                source_type=source_type,
                aggregation_type=aggregation_type,
                unit=unit or None,
                sort_order=sort_order,
                is_active=is_active
            )
            db.session.add(row)
            db.session.commit()
            flash("KPI master created ✅", "success")
            return redirect(url_for("kpi_master.kpi_master"))

        if action == "update":
            row = KpiMaster.query.get_or_404(int(request.form.get("kpi_id")))
            row.name = _clean(request.form.get("name")) or row.name
            row.code = (_clean(request.form.get("code")) or row.code).lower().replace(" ", "_")
            row.description = _clean(request.form.get("description")) or None
            row.source_type = (_clean(request.form.get("source_type")) or row.source_type).upper()
            row.aggregation_type = (_clean(request.form.get("aggregation_type")) or row.aggregation_type).upper()
            row.unit = _clean(request.form.get("unit")) or None
            row.sort_order = int(request.form.get("sort_order") or row.sort_order or 1)
            row.is_active = bool(request.form.get("is_active"))
            db.session.commit()
            flash("KPI master updated ✅", "success")
            return redirect(url_for("kpi_master.kpi_master"))

        if action == "delete":
            row = KpiMaster.query.get_or_404(int(request.form.get("kpi_id")))
            db.session.delete(row)
            db.session.commit()
            flash("KPI master deleted ✅", "success")
            return redirect(url_for("kpi_master.kpi_master"))

    kpis = KpiMaster.query.order_by(KpiMaster.sort_order.asc(), KpiMaster.name.asc()).all()
    return render_template("admin/kpi_master.html", kpis=kpis)


# -------------------------------------------------------
# KPI Assignments
# -------------------------------------------------------
@kpi_bp.route("/kpi/assignments", methods=["GET", "POST"])
@login_required
@require_perm("kpi.manage")
def kpi_assignments():
    if request.method == "POST":
        action = request.form.get("action")

        if action == "bulk_upsert":
            assignment_type = _clean(request.form.get("assignment_type")).lower()
            designation_id_raw = _clean(request.form.get("designation_id"))
            user_id_raw = _clean(request.form.get("user_id"))

            designation_id = int(designation_id_raw) if designation_id_raw.isdigit() else None
            user_id = int(user_id_raw) if user_id_raw.isdigit() else None

            if assignment_type not in ("designation", "user"):
                flash("Invalid assignment type.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            if assignment_type == "designation" and not designation_id:
                flash("Designation is required.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            if assignment_type == "user" and not user_id:
                flash("User is required.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            kpis = (
                KpiMaster.query
                .filter_by(is_active=True)
                .order_by(KpiMaster.sort_order.asc(), KpiMaster.name.asc())
                .all()
            )

            existing_rows = _get_assignment_target_rows(
                assignment_type=assignment_type,
                designation_id=designation_id,
                user_id=user_id,
            )
            existing_map = {row.kpi_id: row for row in existing_rows}

            selected_kpi_ids = []
            total_active_weightage = Decimal("0")

            for k in kpis:
                checked = bool(request.form.get(f"assign_{k.id}"))
                if not checked:
                    continue

                target_mode = _clean(request.form.get(f"target_mode_{k.id}")) or "monthly"
                if target_mode not in ("monthly", "monthly_quarterly", "monthly_quarterly_yearly"):
                    target_mode = "monthly"

                monthly_target = _to_decimal(request.form.get(f"monthly_target_{k.id}"))
                quarterly_target = _to_decimal(request.form.get(f"quarterly_target_{k.id}"))
                yearly_target = _to_decimal(request.form.get(f"yearly_target_{k.id}"))
                weightage = _to_decimal(request.form.get(f"weightage_{k.id}"))
                effective_from = _parse_date(request.form.get(f"effective_from_{k.id}"))
                effective_to = _parse_date(request.form.get(f"effective_to_{k.id}"))
                is_active = bool(request.form.get(f"is_active_{k.id}"))

                if effective_from and effective_to and effective_to < effective_from:
                    flash(f"Effective To cannot be earlier than Effective From for KPI '{k.name}'.", "danger")
                    return redirect(url_for(
                        "kpi_master.kpi_assignments",
                        assignment_type=assignment_type,
                        designation_id=designation_id if designation_id else "",
                        user_id=user_id if user_id else "",
                    ))

                if is_active:
                    total_active_weightage += weightage

                selected_kpi_ids.append(k.id)

            if not selected_kpi_ids:
                flash("Please select at least one KPI.", "danger")
                return redirect(url_for(
                    "kpi_master.kpi_assignments",
                    assignment_type=assignment_type,
                    designation_id=designation_id if designation_id else "",
                    user_id=user_id if user_id else "",
                ))

            if total_active_weightage > Decimal("100"):
                flash(
                    f"Total active weightage cannot exceed 100%. Current selected total is {total_active_weightage}%.",
                    "danger"
                )
                return redirect(url_for(
                    "kpi_master.kpi_assignments",
                    assignment_type=assignment_type,
                    designation_id=designation_id if designation_id else "",
                    user_id=user_id if user_id else "",
                ))

            created_count = 0
            updated_count = 0
            deleted_count = 0

            # create/update checked rows
            for k in kpis:
                checked = bool(request.form.get(f"assign_{k.id}"))
                existing = existing_map.get(k.id)

                if not checked:
                    continue

                target_mode = _clean(request.form.get(f"target_mode_{k.id}")) or "monthly"
                if target_mode not in ("monthly", "monthly_quarterly", "monthly_quarterly_yearly"):
                    target_mode = "monthly"

                monthly_target = _to_decimal(request.form.get(f"monthly_target_{k.id}"))
                quarterly_target = _to_decimal(request.form.get(f"quarterly_target_{k.id}"))
                yearly_target = _to_decimal(request.form.get(f"yearly_target_{k.id}"))
                weightage = _to_decimal(request.form.get(f"weightage_{k.id}"))
                effective_from = _parse_date(request.form.get(f"effective_from_{k.id}"))
                effective_to = _parse_date(request.form.get(f"effective_to_{k.id}"))
                is_active = bool(request.form.get(f"is_active_{k.id}"))

                if existing:
                    existing.target_mode = target_mode
                    existing.monthly_target = monthly_target
                    existing.quarterly_target = quarterly_target
                    existing.yearly_target = yearly_target
                    existing.weightage = weightage
                    existing.effective_from = effective_from
                    existing.effective_to = effective_to
                    existing.is_active = is_active
                    updated_count += 1
                else:
                    row = KpiAssignment(
                        kpi_id=k.id,
                        assignment_type=assignment_type,
                        designation_id=designation_id if assignment_type == "designation" else None,
                        user_id=user_id if assignment_type == "user" else None,
                        target_mode=target_mode,
                        monthly_target=monthly_target,
                        quarterly_target=quarterly_target,
                        yearly_target=yearly_target,
                        effective_from=effective_from,
                        effective_to=effective_to,
                        is_active=is_active,
                        weightage=weightage,
                        created_by_id=current_user.id
                    )
                    db.session.add(row)
                    created_count += 1

            # remove unchecked rows for same target
            for existing in existing_rows:
                if existing.kpi_id not in selected_kpi_ids:
                    db.session.delete(existing)
                    deleted_count += 1

            db.session.commit()
            flash(
                f"KPI assignments saved ✅ Created: {created_count}, Updated: {updated_count}, Removed: {deleted_count}",
                "success"
            )
            return redirect(url_for(
                "kpi_master.kpi_assignments",
                assignment_type=assignment_type,
                designation_id=designation_id if designation_id else "",
                user_id=user_id if user_id else "",
            ))

        if action == "update":
            row = KpiAssignment.query.get_or_404(int(request.form.get("assignment_id")))
            row.kpi_id = int(request.form.get("kpi_id") or row.kpi_id)

            assignment_type = _clean(request.form.get("assignment_type")).lower() or row.assignment_type
            row.assignment_type = assignment_type

            designation_id_raw = _clean(request.form.get("designation_id"))
            user_id_raw = _clean(request.form.get("user_id"))

            row.designation_id = int(designation_id_raw) if (assignment_type == "designation" and designation_id_raw.isdigit()) else None
            row.user_id = int(user_id_raw) if (assignment_type == "user" and user_id_raw.isdigit()) else None

            row.target_mode = _clean(request.form.get("target_mode")) or row.target_mode
            row.monthly_target = _to_decimal(request.form.get("monthly_target"), str(row.monthly_target or 0))
            row.quarterly_target = _to_decimal(request.form.get("quarterly_target"), str(row.quarterly_target or 0))
            row.yearly_target = _to_decimal(request.form.get("yearly_target"), str(row.yearly_target or 0))
            row.effective_from = _parse_date(request.form.get("effective_from"))
            row.effective_to = _parse_date(request.form.get("effective_to"))
            row.is_active = bool(request.form.get("is_active"))
            row.weightage = _to_decimal(request.form.get("weightage"), str(row.weightage or 0))

            if row.assignment_type == "designation" and not row.designation_id:
                flash("Designation is required for designation-wise assignment.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            if row.assignment_type == "user" and not row.user_id:
                flash("User is required for user-wise assignment.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            if row.effective_from and row.effective_to and row.effective_to < row.effective_from:
                flash("Effective To cannot be earlier than Effective From.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            check_payload = {
                "assignment_type": row.assignment_type,
                "user_id": row.user_id,
                "designation_id": row.designation_id,
                "exclude_id": row.id,
            }
            ok, existing_total = _validate_total_weightage(check_payload, row.weightage if row.is_active else Decimal("0"))
            if not ok:
                flash(f"Total weightage exceeds 100%. Existing active total is {existing_total}%.", "danger")
                return redirect(url_for("kpi_master.kpi_assignments"))

            db.session.commit()
            flash("KPI assignment updated ✅", "success")
            return redirect(url_for("kpi_master.kpi_assignments"))

        if action == "delete":
            row = KpiAssignment.query.get_or_404(int(request.form.get("assignment_id")))
            db.session.delete(row)
            db.session.commit()
            flash("KPI assignment deleted ✅", "success")
            return redirect(url_for("kpi_master.kpi_assignments"))

    selected_assignment_type = _clean(request.args.get("assignment_type") or "user").lower()
    if selected_assignment_type not in ("designation", "user"):
        selected_assignment_type = "user"

    selected_designation_id_raw = _clean(request.args.get("designation_id"))
    selected_user_id_raw = _clean(request.args.get("user_id"))

    selected_designation_id = int(selected_designation_id_raw) if selected_designation_id_raw.isdigit() else None
    selected_user_id = int(selected_user_id_raw) if selected_user_id_raw.isdigit() else None

    kpis = KpiMaster.query.filter_by(is_active=True).order_by(KpiMaster.sort_order.asc(), KpiMaster.name.asc()).all()
    designations = Designation.query.filter_by(is_active=True).order_by(Designation.name.asc()).all()
    users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()

    assignments = (
        KpiAssignment.query
        .join(KpiMaster, KpiMaster.id == KpiAssignment.kpi_id)
        .outerjoin(Designation, Designation.id == KpiAssignment.designation_id)
        .outerjoin(User, User.id == KpiAssignment.user_id)
        .order_by(
            KpiAssignment.assignment_type.asc(),
            User.name.asc(),
            Designation.name.asc(),
            KpiMaster.sort_order.asc(),
            KpiMaster.name.asc(),
            KpiAssignment.id.desc()
        )
        .all()
    )

    grouped_assignments = _group_assignments_for_view(assignments)

    existing_target_rows = []
    existing_target_map = {}
    current_target_weightage = Decimal("0")
    current_target_label = ""

    if selected_assignment_type == "designation" and selected_designation_id:
        existing_target_rows = _get_assignment_target_rows(
            assignment_type="designation",
            designation_id=selected_designation_id,
            user_id=None
        )
        d = Designation.query.get(selected_designation_id)
        current_target_label = f"Designation: {d.name}" if d else "Designation"
    elif selected_assignment_type == "user" and selected_user_id:
        existing_target_rows = _get_assignment_target_rows(
            assignment_type="user",
            designation_id=None,
            user_id=selected_user_id
        )
        u = User.query.get(selected_user_id)
        current_target_label = f"User: {u.name}" if u else "User"

    existing_target_map = {row.kpi_id: row for row in existing_target_rows}
    current_target_weightage = sum(
        (_to_decimal(row.weightage) for row in existing_target_rows if row.is_active),
        Decimal("0")
    )

    return render_template(
        "admin/kpi_assignments.html",
        kpis=kpis,
        designations=designations,
        users=users,
        assignments=assignments,
        grouped_assignments=grouped_assignments,
        selected_assignment_type=selected_assignment_type,
        selected_designation_id=selected_designation_id,
        selected_user_id=selected_user_id,
        existing_target_map=existing_target_map,
        current_target_weightage=current_target_weightage,
        current_target_label=current_target_label,
    )

# -------------------------------------------------------
# KPI Targets
# -------------------------------------------------------
@kpi_bp.route("/kpi/targets", methods=["GET", "POST"])
@login_required
@require_perm("kpi.manage")
def kpi_targets():
    if request.method == "POST":
        action = request.form.get("action")

        if action == "update":
            row = KpiAssignment.query.get_or_404(int(request.form.get("assignment_id")))

            row.target_mode = _clean(request.form.get("target_mode")) or row.target_mode
            row.monthly_target = _to_decimal(request.form.get("monthly_target"), str(row.monthly_target or 0))
            row.quarterly_target = _to_decimal(request.form.get("quarterly_target"), str(row.quarterly_target or 0))
            row.yearly_target = _to_decimal(request.form.get("yearly_target"), str(row.yearly_target or 0))
            row.weightage = _to_decimal(request.form.get("weightage"), str(row.weightage or 0))
            row.effective_from = _parse_date(request.form.get("effective_from"))
            row.effective_to = _parse_date(request.form.get("effective_to"))
            row.is_active = bool(request.form.get("is_active"))

            if row.target_mode not in ("monthly", "monthly_quarterly", "monthly_quarterly_yearly"):
                flash("Invalid target mode.", "danger")
                return redirect(url_for("kpi_master.kpi_targets"))

            check_payload = {
                "assignment_type": row.assignment_type,
                "user_id": row.user_id,
                "designation_id": row.designation_id,
                "exclude_id": row.id,
            }
            ok, existing_total = _validate_total_weightage(check_payload, row.weightage)
            if not ok:
                flash(f"Total weightage exceeds 100%. Existing active total is {existing_total}%.", "danger")
                return redirect(url_for("kpi_master.kpi_targets"))

            db.session.commit()
            flash("KPI target updated ✅", "success")
            return redirect(url_for("kpi_master.kpi_targets"))

        if action == "delete":
            row = KpiAssignment.query.get_or_404(int(request.form.get("assignment_id")))
            db.session.delete(row)
            db.session.commit()
            flash("KPI target deleted ✅", "success")
            return redirect(url_for("kpi_master.kpi_targets"))

    assignment_type = _clean(request.args.get("assignment_type")).lower()
    kpi_id = _clean(request.args.get("kpi_id"))
    designation_id = _clean(request.args.get("designation_id"))
    user_id = _clean(request.args.get("user_id"))
    active = _clean(request.args.get("active"))

    qs = (
        KpiAssignment.query
        .join(KpiMaster, KpiMaster.id == KpiAssignment.kpi_id)
        .outerjoin(Designation, Designation.id == KpiAssignment.designation_id)
        .outerjoin(User, User.id == KpiAssignment.user_id)
        .order_by(
            KpiMaster.sort_order.asc(),
            KpiMaster.name.asc(),
            KpiAssignment.assignment_type.asc(),
            KpiAssignment.id.desc()
        )
    )

    if assignment_type in ("designation", "user"):
        qs = qs.filter(KpiAssignment.assignment_type == assignment_type)

    if kpi_id.isdigit():
        qs = qs.filter(KpiAssignment.kpi_id == int(kpi_id))

    if designation_id.isdigit():
        qs = qs.filter(KpiAssignment.designation_id == int(designation_id))

    if user_id.isdigit():
        qs = qs.filter(KpiAssignment.user_id == int(user_id))

    if active == "1":
        qs = qs.filter(KpiAssignment.is_active == True)
    elif active == "0":
        qs = qs.filter(KpiAssignment.is_active == False)

    assignments = qs.all()
    kpis = KpiMaster.query.filter_by(is_active=True).order_by(KpiMaster.sort_order.asc(), KpiMaster.name.asc()).all()
    designations = Designation.query.filter_by(is_active=True).order_by(Designation.name.asc()).all()
    users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()

    return render_template(
        "admin/kpi_targets.html",
        assignments=assignments,
        kpis=kpis,
        designations=designations,
        users=users,
        assignment_type=assignment_type,
        kpi_id=kpi_id,
        designation_id=designation_id,
        user_id=user_id,
        active=active
    )


# -------------------------------------------------------
# KPI Dashboard
# -------------------------------------------------------
@kpi_bp.route("/kpi/dashboard", methods=["GET"])
@login_required
@require_perm("kpi.view_self")
def kpi_dashboard():
    today = date.today()

    period_type = _clean(request.args.get("period_type") or "monthly").lower()
    if period_type not in ("monthly", "quarterly", "yearly"):
        period_type = "monthly"

    year = int(request.args.get("year") or today.year)
    month = int(request.args.get("month") or today.month)
    quarter = int(request.args.get("quarter") or (((today.month - 1) // 3) + 1))

    allowed_user_ids = _allowed_dashboard_user_ids()

    selected_user_id_raw = _clean(request.args.get("user_id"))
    if selected_user_id_raw.isdigit():
        selected_user_id = int(selected_user_id_raw)
    else:
        selected_user_id = current_user.id

    if allowed_user_ids is not None and selected_user_id not in allowed_user_ids:
        selected_user_id = current_user.id

    selected_user = User.query.get_or_404(selected_user_id)

    own_rows = _build_self_dashboard_rows(
        selected_user,
        period_type=period_type,
        year=year,
        month=month,
        quarter=quarter
    )

    team_rows = []
    if current_user.has_perm("kpi.view_team") or current_user.has_perm("kpi.view_all"):
        team_rows = _build_team_dashboard_rows(
            selected_user,
            period_type=period_type,
            year=year,
            month=month,
            quarter=quarter
        )

    if allowed_user_ids is None:
        users = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    else:
        users = User.query.filter(User.id.in_(allowed_user_ids)).order_by(User.name.asc()).all()

    own_total_weighted_score = sum(
        (row.get("weighted_score", Decimal("0")) for row in own_rows),
        Decimal("0")
    )
    own_total_weightage = sum(
        (row.get("weightage", Decimal("0")) for row in own_rows),
        Decimal("0")
    )

    return render_template(
        "admin/kpi_dashboard.html",
        own_rows=own_rows,
        team_rows=team_rows,
        users=users,
        selected_user=selected_user,
        period_type=period_type,
        year=year,
        month=month,
        quarter=quarter,
        today=today,
        own_total_weighted_score=own_total_weighted_score,
        own_total_weightage=own_total_weightage
    )

@kpi_bp.route("/kpi/assignment-weightage-info", methods=["GET"])
@login_required
@require_perm("kpi.manage")
def kpi_assignment_weightage_info():
    assignment_type = _clean(request.args.get("assignment_type")).lower()
    designation_id_raw = _clean(request.args.get("designation_id"))
    user_id_raw = _clean(request.args.get("user_id"))

    qs = KpiAssignment.query.filter(KpiAssignment.is_active == True)

    if assignment_type == "designation":
        if not designation_id_raw.isdigit():
            return jsonify({"ok": False, "message": "Invalid designation"}), 400
        qs = qs.filter(
            KpiAssignment.assignment_type == "designation",
            KpiAssignment.designation_id == int(designation_id_raw)
        )

    elif assignment_type == "user":
        if not user_id_raw.isdigit():
            return jsonify({"ok": False, "message": "Invalid user"}), 400
        qs = qs.filter(
            KpiAssignment.assignment_type == "user",
            KpiAssignment.user_id == int(user_id_raw)
        )
    else:
        return jsonify({"ok": False, "message": "Invalid assignment type"}), 400

    total_weightage = qs.with_entities(
        func.coalesce(func.sum(KpiAssignment.weightage), 0)
    ).scalar() or 0

    return jsonify({
        "ok": True,
        "total_weightage": str(_to_decimal(total_weightage))
    })

@kpi_bp.route("/kpi/calculation-details", methods=["GET"])
@login_required
@require_perm("kpi.view_self")
def kpi_calculation_details():
    today = date.today()

    kpi_code = _clean(request.args.get("kpi_code"))
    period_type = _clean(request.args.get("period_type") or "monthly").lower()

    if period_type not in ("monthly", "quarterly", "yearly"):
        period_type = "monthly"

    year = int(request.args.get("year") or today.year)
    month = int(request.args.get("month") or today.month)
    quarter = int(request.args.get("quarter") or (((today.month - 1) // 3) + 1))

    allowed_user_ids = _allowed_dashboard_user_ids()

    selected_user_id_raw = _clean(request.args.get("user_id"))
    selected_user_id = int(selected_user_id_raw) if selected_user_id_raw.isdigit() else current_user.id

    if allowed_user_ids is not None and selected_user_id not in allowed_user_ids:
        selected_user_id = current_user.id

    selected_user = User.query.get_or_404(selected_user_id)

    start_date, end_date = _period_bounds(period_type, year, month, quarter)

    scope_user_ids = _team_user_ids(selected_user.id, include_self=True)

    details = _get_kpi_calculation_details(
        kpi_code=kpi_code,
        user_ids=scope_user_ids,
        start_date=start_date,
        end_date=end_date
    )

    return jsonify({
        "ok": True,
        "kpi_code": kpi_code,
        "period": {
            "start_date": start_date.strftime("%d-%m-%Y"),
            "end_date": end_date.strftime("%d-%m-%Y"),
        },
        "summary": {
            "crystal_nexus_total": _money_json(details["cn_total"]),
            "pms_total": _money_json(details["pms_total"]),
            "grand_total": _money_json(details["grand_total"]),
            "crystal_nexus_count": len(details["cn_rows"]),
            "pms_count": len(details["pms_rows"]),
        },
        "cn_rows": details["cn_rows"],
        "pms_rows": details["pms_rows"],
    })

@kpi_bp.route("/kpi/cluster-comparison", methods=["GET"])
@login_required
@require_perm("kpi.view_team")
def kpi_cluster_comparison():
    today = date.today()

    start_year = int(request.args.get("start_year") or today.year)
    start_month = int(request.args.get("start_month") or 1)

    end_year = int(request.args.get("end_year") or today.year)
    end_month = int(request.args.get("end_month") or today.month)

    selected_manager_id_raw = _clean(request.args.get("manager_id"))
    selected_manager_id = int(selected_manager_id_raw) if selected_manager_id_raw.isdigit() else current_user.id

    allowed_user_ids = _allowed_dashboard_user_ids()

    if allowed_user_ids is not None and selected_manager_id not in allowed_user_ids:
        selected_manager_id = current_user.id

    selected_manager = User.query.get_or_404(selected_manager_id)

    cluster_user_ids = _team_user_ids(selected_manager.id, include_self=True)

    if allowed_user_ids is not None:
        cluster_user_ids = [uid for uid in cluster_user_ids if uid in allowed_user_ids]

    users = (
        User.query
        .filter(User.id.in_(cluster_user_ids))
        .filter(User.is_active == True)
        .order_by(User.name.asc())
        .all()
    )

    months = _month_range(start_year, start_month, end_year, end_month)

    comparison_rows = []

    for user in users:
        month_scores = []
        total_score = Decimal("0")
        score_count = Decimal("0")

        for month_data in months:
            result = _total_weighted_score_for_user_month(
                user=user,
                year=month_data["year"],
                month=month_data["month"]
            )

            score = result["score"]
            weightage = result["weightage"]

            month_scores.append({
                "year": month_data["year"],
                "month": month_data["month"],
                "label": month_data["label"],
                "score": score,
                "weightage": weightage
            })

            total_score += score
            score_count += Decimal("1")

        average_score = Decimal("0")
        if score_count > 0:
            average_score = total_score / score_count

        comparison_rows.append({
            "user": user,
            "month_scores": month_scores,
            "average_score": average_score
        })

    comparison_rows.sort(
        key=lambda x: x["average_score"],
        reverse=True
    )

    managers = []
    if current_user.has_perm("kpi.view_all"):
        managers = User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    else:
        managers = User.query.filter(User.id.in_(allowed_user_ids or [current_user.id])).order_by(User.name.asc()).all()

    return render_template(
        "admin/kpi_cluster_comparison.html",
        managers=managers,
        selected_manager=selected_manager,
        months=months,
        comparison_rows=comparison_rows,
        start_year=start_year,
        start_month=start_month,
        end_year=end_year,
        end_month=end_month,
        today=today
    )