from __future__ import annotations

from datetime import timedelta

from django.db.models import Count, IntegerField, Q, Sum, Value
from django.db.models.functions import Coalesce, TruncDate, TruncMonth, TruncWeek
from django.utils import timezone

from contract.models import (
    AppNotification,
    Contract,
    FarmerGroup,
    FieldOfficerAssignment,
    GroupContract,
    GroupMembership,
    Input,
    InputPackage,
    InputVariety,
    PaymentSchedule,
    User,
)
from market.models import (
    CompanyInvitation,
    CompanyMember,
    CompanyProfile,
    FarmerMarketCommissionPayout,
    FarmerMarketListing,
    FarmerMarketListingOffer,
    FarmerMarketListingPayment,
    MarketCategory,
    MarketOrder,
    MarketOrderItem,
    MarketProduct,
    MarketSellerOrder,
    SellerProfile,
)
from payments.models import GroupPayment, MarketplacePayment, Payment

from contract.services.dashboard_widgets import safe_reverse


CHART_COLORS = {
    "emerald": ["#22c55e", "#16a34a", "#15803d", "#86efac", "#14532d", "#4ade80"],
    "amber": ["#f59e0b", "#f97316", "#facc15", "#fdba74", "#fbbf24", "#fb923c"],
    "blue": ["#3b82f6", "#2563eb", "#60a5fa", "#1d4ed8", "#93c5fd", "#0ea5e9"],
    "slate": ["#334155", "#475569", "#64748b", "#94a3b8", "#1f2937", "#0f172a"],
    "rose": ["#e11d48", "#f43f5e", "#fb7185", "#be123c", "#fecdd3", "#ef4444"],
    "mixed": ["#22c55e", "#3b82f6", "#f59e0b", "#e11d48", "#8b5cf6", "#14b8a6"],
}


def _int(value) -> int:
    return int(value or 0)


def _currency(value) -> str:
    return f"KES {_int(value):,}"


def _choice_label(choices, value: str) -> str:
    return dict(choices).get(value, str(value).replace("_", " ").title())


def _kpi(label: str, value: str, meta: str, icon: str, *, tone: str = "emerald", href: str = "", trend: str = "") -> dict:
    return {
        "label": label,
        "value": value,
        "meta": meta,
        "icon": icon,
        "tone": tone,
        "href": href,
        "trend": trend,
    }


def _summary_card(title: str, body: str, icon: str, *, tone: str = "emerald") -> dict:
    return {
        "title": title,
        "body": body,
        "icon": icon,
        "tone": tone,
    }


def _table(title: str, columns: list[str], rows: list[dict], *, subtitle: str = "", empty: str = "No records yet.") -> dict:
    return {
        "title": title,
        "subtitle": subtitle,
        "columns": columns,
        "rows": rows,
        "empty": empty,
    }


def _activity_item(title: str, meta: str, priority: str, *, url: str = "", action_label: str = "Open") -> dict:
    return {
        "title": title,
        "meta": meta,
        "priority": priority,
        "url": url,
        "action_label": action_label,
    }


def _chart(
    chart_id: str,
    title: str,
    chart_type: str,
    labels: list[str],
    datasets: list[dict],
    *,
    subtitle: str = "",
    height: str = "300px",
    options: dict | None = None,
) -> dict:
    has_data = any(any(_int(point) > 0 for point in dataset.get("data", [])) for dataset in datasets)
    return {
        "id": chart_id,
        "script_id": f"chart-config-{chart_id}",
        "title": title,
        "subtitle": subtitle,
        "height": height,
        "has_data": has_data,
        "config": {
            "type": chart_type,
            "data": {
                "labels": labels,
                "datasets": datasets,
            },
            "options": options or {},
        },
    }


def _section(
    section_id: str,
    title: str,
    description: str,
    *,
    cards: list[dict] | None = None,
    charts: list[dict] | None = None,
    tables: list[dict] | None = None,
    highlights: list[str] | None = None,
) -> dict:
    return {
        "id": section_id,
        "title": title,
        "description": description,
        "cards": cards or [],
        "charts": charts or [],
        "tables": tables or [],
        "highlights": highlights or [],
    }


def _recent_activity_queryset(user, *, global_scope: bool):
    qs = AppNotification.objects.filter(is_hidden=False).order_by("-created_at", "-id")
    if not global_scope:
        qs = qs.filter(recipient=user)
    return qs


def _build_recent_activity(user, *, global_scope: bool = False, limit: int = 6) -> list[dict]:
    items = []
    for notification in _recent_activity_queryset(user, global_scope=global_scope)[:limit]:
        meta = notification.created_at.strftime("%d %b %Y, %I:%M %p")
        items.append(
            _activity_item(
                notification.title,
                meta,
                notification.priority,
                url=safe_reverse("contract_market_place:notification_open", args=[notification.id]),
                action_label=notification.action_label or "Open",
            )
        )
    return items


def _status_breakdown(queryset, field_name: str, choices) -> tuple[list[str], list[int]]:
    counts = dict(
        queryset.values(field_name).annotate(total=Count("id")).values_list(field_name, "total")
    )
    labels = []
    data = []
    for value, label in choices:
        total = _int(counts.get(value))
        if total:
            labels.append(label)
            data.append(total)
    if not labels:
        labels = [label for value, label in choices]
        data = [0 for _value, _label in choices]
    return labels, data


def _series_settings(days: int):
    if days <= 31:
        return TruncDate, "%d %b"
    if days <= 120:
        return TruncWeek, "Week of %d %b"
    return TruncMonth, "%b %Y"


def _build_time_series(queryset, *, date_field: str, days: int, sum_field: str | None = None) -> dict:
    trunc, label_format = _series_settings(days)
    start = timezone.now() - timedelta(days=days)
    filtered = queryset.filter(**{f"{date_field}__gte": start})
    rows = (
        filtered.annotate(bucket=trunc(date_field))
        .values("bucket")
        .annotate(total=Count("id") if sum_field is None else Coalesce(Sum(sum_field), Value(0), output_field=IntegerField()))
        .order_by("bucket")
    )
    points = []
    mapping = {}
    for row in rows:
        bucket = row["bucket"]
        label = bucket.strftime(label_format)
        total = _int(row["total"])
        points.append((bucket, label, total))
        mapping[bucket] = total
    return {
        "points": points,
        "mapping": mapping,
    }


def _merge_series(*series) -> tuple[list[str], list[list[int]]]:
    all_buckets = []
    for item in series:
        for bucket, label, _value in item["points"]:
            all_buckets.append((bucket, label))
    ordered = []
    seen = set()
    for bucket, label in sorted(all_buckets, key=lambda row: row[0]):
        if bucket in seen:
            continue
        seen.add(bucket)
        ordered.append((bucket, label))
    labels = [label for _bucket, label in ordered]
    dataset_rows = []
    for item in series:
        dataset_rows.append([_int(item["mapping"].get(bucket)) for bucket, _label in ordered])
    return labels, dataset_rows


def _build_admin_reports(user, days: int) -> dict:
    start = timezone.now() - timedelta(days=days)
    active_farmers = User.objects.filter(type=User.Types.FARMER, is_active=True).count()
    active_buyers = User.objects.filter(type=User.Types.BUYER, is_active=True).count()
    active_field_officers = User.objects.filter(type=User.Types.FIELD_OFFICER, is_active=True).count()
    approved_sellers = SellerProfile.objects.filter(status=SellerProfile.Status.APPROVED).count()
    pending_users = User.objects.filter(is_active=False).count()
    pending_sellers = SellerProfile.objects.filter(status=SellerProfile.Status.PENDING).count()
    pending_products = MarketProduct.objects.filter(status=MarketProduct.Status.PENDING_APPROVAL).count()
    pending_listings = FarmerMarketListing.objects.filter(
        status__in=[
            FarmerMarketListing.Status.PENDING_APPROVAL,
            FarmerMarketListing.Status.CHANGES_REQUESTED,
            FarmerMarketListing.Status.AWAITING_PAYMENT,
        ]
    ).count()
    total_contracts = Contract.objects.count()
    active_contracts = Contract.objects.filter(status="ACTIVE").count()
    pending_signatures = Contract.objects.filter(status="PENDING_SIGN").count()
    active_group_contracts = GroupContract.objects.filter(status="ACTIVE").count()
    overdue_schedules = PaymentSchedule.objects.filter(status="OVERDUE").count()
    total_contract_value = _int(Contract.objects.aggregate(total=Sum("total_amount")).get("total"))
    contract_payments_collected = _int(Payment.objects.filter(status="COMPLETED").aggregate(total=Sum("amount")).get("total"))
    paid_market_orders = MarketOrder.objects.filter(payment_status=MarketOrder.PaymentStatus.PAID)
    marketplace_gmv = _int(paid_market_orders.aggregate(total=Sum("grand_total")).get("total"))
    listing_fee_revenue = _int(
        FarmerMarketListingPayment.objects.filter(status=FarmerMarketListingPayment.StatusChoices.PAID).aggregate(
            total=Sum("amount_inclusive")
        ).get("total")
    )
    marketplace_commission_value = _int(
        MarketSellerOrder.objects.filter(parent_order__payment_status=MarketOrder.PaymentStatus.PAID).aggregate(
            total=Sum("commission_amount_placeholder")
        ).get("total")
    )
    field_commission_due = max(
        _int(
            FarmerMarketListingPayment.objects.filter(status=FarmerMarketListingPayment.StatusChoices.PAID).aggregate(
                total=Sum("field_officer_commission_amount")
            ).get("total")
        )
        - _int(FarmerMarketCommissionPayout.objects.aggregate(total=Sum("amount_paid")).get("total")),
        0,
    )
    failed_payments = (
        Payment.objects.filter(status="FAILED").count()
        + MarketplacePayment.objects.filter(status=MarketplacePayment.StatusChoices.FAILED).count()
        + FarmerMarketListingPayment.objects.filter(status=FarmerMarketListingPayment.StatusChoices.FAILED).count()
    )
    collection_rate = round((contract_payments_collected / total_contract_value * 100) if total_contract_value else 0, 1)

    contract_labels, contract_data = _status_breakdown(Contract.objects.all(), "status", Contract.STATUS_CHOICES)
    group_contract_labels, group_contract_data = _status_breakdown(
        GroupContract.objects.all(), "status", GroupContract.STATUS_CHOICES
    )
    role_distribution_labels = ["Farmers", "Buyers", "Field Officers", "Approved Sellers", "Admins"]
    role_distribution_data = [
        active_farmers,
        active_buyers,
        active_field_officers,
        approved_sellers,
        User.objects.filter(type=User.Types.ADMIN, is_active=True).count()
        + User.objects.filter(is_superuser=True, is_active=True).exclude(type=User.Types.ADMIN).count(),
    ]
    market_payment_labels, market_payment_data = _status_breakdown(
        MarketplacePayment.objects.all(),
        "status",
        MarketplacePayment.StatusChoices.choices,
    )

    contracts_series = _build_time_series(Contract.objects.all(), date_field="created_at", days=days)
    orders_series = _build_time_series(MarketOrder.objects.all(), date_field="created_at", days=days)
    payments_series = _build_time_series(
        Payment.objects.filter(status="COMPLETED"),
        date_field="created_at",
        days=days,
        sum_field="amount",
    )
    trend_labels, trend_datasets = _merge_series(contracts_series, orders_series, payments_series)

    officer_rows = (
        FieldOfficerAssignment.objects.values(
            "field_officer_id",
            "field_officer__first_name",
            "field_officer__last_name",
        )
        .annotate(farmers=Count("farmer", distinct=True))
        .order_by("-farmers")[:6]
    )
    officer_labels = []
    officer_values = []
    for row in officer_rows:
        name = " ".join(
            part for part in [row.get("field_officer__first_name"), row.get("field_officer__last_name")] if part
        ).strip() or f"Officer {row['field_officer_id']}"
        officer_labels.append(name)
        officer_values.append(_int(row["farmers"]))

    top_sellers = list(
        MarketSellerOrder.objects.filter(parent_order__payment_status=MarketOrder.PaymentStatus.PAID)
        .values("seller__display_name")
        .annotate(
            order_count=Count("id"),
            subtotal_value=Coalesce(Sum("subtotal_amount"), Value(0), output_field=IntegerField()),
        )
        .order_by("-subtotal_value", "-order_count")[:5]
    )
    top_products = list(
        MarketOrderItem.objects.values("product_name_snapshot")
        .annotate(lines_sold=Count("id"), subtotal_value=Coalesce(Sum("line_subtotal"), Value(0), output_field=IntegerField()))
        .order_by("-lines_sold", "-subtotal_value")[:5]
    )
    recent_contracts = Contract.objects.select_related("farmer").order_by("-created_at")[:6]
    recent_payments = Payment.objects.select_related("farmer", "contract").order_by("-created_at")[:6]

    summary_cards = [
        _summary_card(
            "Platform breadth",
            f"{active_farmers} active farmers, {active_buyers} active buyers, and {approved_sellers} approved sellers are currently in the system.",
            "fa-network-wired",
            tone="emerald",
        ),
        _summary_card(
            "Collections health",
            f"Contract collections sit at {collection_rate}% with {_currency(contract_payments_collected)} collected and {overdue_schedules} overdue schedules needing attention.",
            "fa-hand-holding-dollar",
            tone="amber",
        ),
        _summary_card(
            "Marketplace visibility",
            f"{pending_sellers} seller applications, {pending_products} products, and {pending_listings} farmer listings are still waiting in moderation queues.",
            "fa-magnifying-glass-chart",
            tone="blue",
        ),
    ]

    sections = [
        _section(
            "board-metrics",
            "Board Metrics",
            "Commercial and risk signals across contracts, marketplace payments, and moderation queues.",
            cards=[
                _kpi("Contract portfolio", _currency(total_contract_value), "Total contract value recorded in the platform.", "fa-file-invoice-dollar", tone="emerald", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Collections received", _currency(contract_payments_collected), "Completed contract collections.", "fa-money-bill-trend-up", tone="blue", href=safe_reverse("payments:farmer_payment_list"), trend=f"{collection_rate}% collection rate"),
                _kpi("Marketplace GMV", _currency(marketplace_gmv), "Paid marketplace order value.", "fa-store", tone="emerald", href=safe_reverse("market:market_admin_order_queue")),
                _kpi("Listing fee revenue", _currency(listing_fee_revenue), "Paid farmer listing fees collected.", "fa-receipt", tone="amber", href=safe_reverse("market:farmer_listing_approval_list")),
                _kpi("Seller commissions", _currency(marketplace_commission_value), "Captured seller order commission placeholders.", "fa-percent", tone="slate", href=safe_reverse("contract_market_place:interest_rate_list")),
                _kpi("Field commission due", _currency(field_commission_due), "Outstanding field-officer commission balance.", "fa-user-tie", tone="rose", href=safe_reverse("market:farmer_listing_approval_list")),
            ],
            charts=[
                _chart(
                    "admin-activity-trend",
                    "Platform activity trend",
                    "line",
                    trend_labels,
                    [
                        {
                            "label": "Contracts created",
                            "data": trend_datasets[0],
                            "borderColor": CHART_COLORS["emerald"][0],
                            "backgroundColor": "rgba(34, 197, 94, 0.12)",
                            "tension": 0.35,
                            "fill": False,
                        },
                        {
                            "label": "Marketplace orders",
                            "data": trend_datasets[1],
                            "borderColor": CHART_COLORS["blue"][0],
                            "backgroundColor": "rgba(59, 130, 246, 0.12)",
                            "tension": 0.35,
                            "fill": False,
                        },
                        {
                            "label": "Completed payments (KES)",
                            "data": trend_datasets[2],
                            "borderColor": CHART_COLORS["amber"][0],
                            "backgroundColor": "rgba(245, 158, 11, 0.12)",
                            "tension": 0.35,
                            "fill": False,
                            "yAxisID": "y1",
                        },
                    ],
                    subtitle="Selected reporting window across contract creation, marketplace demand, and collections.",
                    options={
                        "responsive": True,
                        "maintainAspectRatio": False,
                        "interaction": {"mode": "index", "intersect": False},
                        "scales": {
                            "y": {"beginAtZero": True},
                            "y1": {"beginAtZero": True, "position": "right", "grid": {"drawOnChartArea": False}},
                        },
                        "plugins": {"legend": {"position": "bottom"}},
                    },
                ),
                _chart(
                    "admin-market-payment-status",
                    "Marketplace payment outcomes",
                    "doughnut",
                    market_payment_labels,
                    [
                        {
                            "label": "Payments",
                            "data": market_payment_data,
                            "backgroundColor": CHART_COLORS["mixed"][: len(market_payment_labels)],
                            "borderWidth": 0,
                        }
                    ],
                    subtitle="Payment results for marketplace transactions.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
            ],
            highlights=[
                f"{pending_users} web accounts still require approval.",
                f"{failed_payments} payment failures are currently recorded across contract and marketplace flows.",
            ],
        ),
        _section(
            "portfolio-health",
            "Portfolio Health",
            "Pipeline mix, user distribution, and field coverage across the platform.",
            cards=[
                _kpi("Active contracts", f"{active_contracts:,}", "Contracts already running.", "fa-file-circle-check", tone="emerald", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Pending signatures", f"{pending_signatures:,}", "Individual contracts still awaiting farmer signature.", "fa-signature", tone="amber", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Group contracts active", f"{active_group_contracts:,}", "Group contracts already activated.", "fa-people-group", tone="blue", href=safe_reverse("contract_market_place:group_contract_list")),
                _kpi("Overdue schedules", f"{overdue_schedules:,}", "Payment schedules already overdue.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
                _kpi("Active farmers", f"{active_farmers:,}", "Farmer accounts currently active.", "fa-seedling", tone="emerald", href=safe_reverse("contract_market_place:user_list", query={"type": "FARMER"})),
                _kpi("Active buyers", f"{active_buyers:,}", "Buyer accounts currently active.", "fa-bag-shopping", tone="blue", href=safe_reverse("market:buyer_list")),
                _kpi("Field officers", f"{active_field_officers:,}", "Field execution staff online in the system.", "fa-user-tie", tone="slate", href=safe_reverse("contract_market_place:field_officer_list")),
                _kpi("Farmer groups", f"{FarmerGroup.objects.filter(is_active=True).count():,}", "Active farmer groups in the platform.", "fa-users", tone="amber", href=safe_reverse("contract_market_place:my_groups")),
            ],
            charts=[
                _chart(
                    "admin-contract-pipeline",
                    "Individual contract pipeline",
                    "bar",
                    contract_labels,
                    [
                        {
                            "label": "Contracts",
                            "data": contract_data,
                            "backgroundColor": CHART_COLORS["emerald"][: len(contract_labels)],
                            "borderRadius": 10,
                        }
                    ],
                    subtitle="Status mix for individual contracts.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
                _chart(
                    "admin-role-distribution",
                    "Role distribution",
                    "doughnut",
                    role_distribution_labels,
                    [
                        {
                            "label": "Users",
                            "data": role_distribution_data,
                            "backgroundColor": CHART_COLORS["mixed"][: len(role_distribution_labels)],
                            "borderWidth": 0,
                        }
                    ],
                    subtitle="Active role coverage across the platform.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
                _chart(
                    "admin-group-contract-pipeline",
                    "Group contract pipeline",
                    "bar",
                    group_contract_labels,
                    [
                        {
                            "label": "Group contracts",
                            "data": group_contract_data,
                            "backgroundColor": CHART_COLORS["amber"][: len(group_contract_labels)],
                            "borderRadius": 10,
                        }
                    ],
                    subtitle="Status mix for group contracts.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
            ],
        ),
        _section(
            "operations-detail",
            "Operations Detail",
            "Top performers, recent movements, and drill-down records for board updates.",
            charts=[
                _chart(
                    "admin-field-officer-productivity",
                    "Field officer coverage",
                    "bar",
                    officer_labels,
                    [
                        {
                            "label": "Assigned farmers",
                            "data": officer_values,
                            "backgroundColor": CHART_COLORS["blue"][: len(officer_labels)],
                            "borderRadius": 10,
                        }
                    ],
                    subtitle="Farmers linked to each field officer.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
            ],
            tables=[
                _table(
                    "Top sellers",
                    ["Seller", "Paid orders", "Subtotal value"],
                    [
                        {
                            "values": [
                                row["seller__display_name"] or "Seller",
                                f"{_int(row['order_count']):,}",
                                _currency(row["subtotal_value"]),
                            ]
                        }
                        for row in top_sellers
                    ],
                    subtitle="Highest seller order movement from paid marketplace orders.",
                    empty="No paid seller orders yet.",
                ),
                _table(
                    "Top products",
                    ["Product", "Order lines", "Subtotal value"],
                    [
                        {
                            "values": [
                                row["product_name_snapshot"] or "Product",
                                f"{_int(row['lines_sold']):,}",
                                _currency(row["subtotal_value"]),
                            ]
                        }
                        for row in top_products
                    ],
                    subtitle="Most active products by order-line volume.",
                    empty="No product sales recorded yet.",
                ),
                _table(
                    "Recent contracts",
                    ["Contract", "Farmer", "Status", "Amount"],
                    [
                        {
                            "values": [
                                f"#{contract.id}",
                                contract.farmer.get_full_name() or contract.farmer.phone_number or "Farmer",
                                contract.get_status_display(),
                                _currency(contract.total_amount),
                            ],
                            "url": safe_reverse("contract_market_place:contract_detail", args=[contract.id]),
                        }
                        for contract in recent_contracts
                    ],
                    subtitle="Latest contract activity.",
                    empty="No contracts have been created yet.",
                ),
                _table(
                    "Recent payments",
                    ["Receipt", "Farmer", "Status", "Amount"],
                    [
                        {
                            "values": [
                                payment.mpesa_receipt_number or f"Payment {payment.id}",
                                payment.farmer.get_full_name() or payment.farmer.phone_number or "Farmer",
                                payment.get_status_display(),
                                _currency(payment.amount),
                            ]
                        }
                        for payment in recent_payments
                    ],
                    subtitle="Most recent contract-side payment records.",
                    empty="No payment records yet.",
                ),
            ],
        ),
    ]

    return {
        "kpis": [
            _kpi("Active farmers", f"{active_farmers:,}", "Farmers currently active on the platform.", "fa-seedling", tone="emerald", href=safe_reverse("contract_market_place:user_list", query={"type": "FARMER"})),
            _kpi("Pending approvals", f"{pending_users:,}", "User accounts still waiting for activation.", "fa-user-clock", tone="amber", href=safe_reverse("contract_market_place:user_list")),
            _kpi("Active contracts", f"{active_contracts:,}", "Contracts already in motion.", "fa-file-contract", tone="blue", href=safe_reverse("contract_market_place:contract_list")),
            _kpi("Marketplace GMV", _currency(marketplace_gmv), "Paid marketplace order value.", "fa-store", tone="emerald", href=safe_reverse("market:market_admin_order_queue")),
            _kpi("Pending sellers", f"{pending_sellers:,}", "Seller applications awaiting review.", "fa-id-card", tone="amber", href=safe_reverse("market:seller_review_list")),
            _kpi("Pending products", f"{pending_products:,}", "Marketplace products awaiting moderation.", "fa-box-open", tone="slate", href=safe_reverse("market:product_review_list")),
        ],
        "alerts": [
            _kpi("Seller queue", f"{pending_sellers:,}", "Review applications before they stall.", "fa-user-clock", tone="amber", href=safe_reverse("market:seller_review_list")),
            _kpi("Product moderation", f"{pending_products:,}", "Approved sellers waiting on product review.", "fa-clipboard-check", tone="blue", href=safe_reverse("market:product_review_list")),
            _kpi("Farmer listing queue", f"{pending_listings:,}", "Listing approvals, changes, or fee follow-up still pending.", "fa-seedling", tone="emerald", href=safe_reverse("market:farmer_listing_approval_list")),
            _kpi("Payment failures", f"{failed_payments:,}", "Failed M-Pesa or marketplace payment attempts.", "fa-circle-xmark", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
        ],
        "summary_cards": summary_cards,
        "sections": sections,
        "activity": _build_recent_activity(user, global_scope=True),
    }


def _build_field_officer_reports(user, days: int) -> dict:
    assigned_farmer_ids = list(
        FieldOfficerAssignment.objects.filter(field_officer=user).values_list("farmer_id", flat=True)
    )
    contracts = Contract.objects.filter(farmer_id__in=assigned_farmer_ids)
    schedules = PaymentSchedule.objects.filter(contract__farmer_id__in=assigned_farmer_ids)
    listings = FarmerMarketListing.objects.filter(field_officer=user)
    offers = FarmerMarketListingOffer.objects.filter(listing__field_officer=user)
    listing_payments = FarmerMarketListingPayment.objects.filter(listing__field_officer=user)
    assigned_orders = MarketSellerOrder.objects.filter(assigned_staff=user)

    assigned_groups = FarmerGroup.objects.filter(
        memberships__user_id__in=assigned_farmer_ids,
        memberships__is_active=True,
        is_active=True,
    ).distinct().count()
    active_contracts = contracts.filter(status="ACTIVE").count()
    pending_signatures = contracts.filter(status="PENDING_SIGN").count()
    overdue_schedules = schedules.filter(status="OVERDUE").count()
    live_listings = listings.filter(status=FarmerMarketListing.Status.LIVE).count()
    pending_listing_reviews = listings.filter(
        status__in=[
            FarmerMarketListing.Status.PENDING_APPROVAL,
            FarmerMarketListing.Status.CHANGES_REQUESTED,
        ]
    ).count()
    sold_listings = listings.filter(status=FarmerMarketListing.Status.SOLD).count()
    active_offers = offers.filter(status=FarmerMarketListingOffer.Status.PENDING).count()
    commission_earned = _int(
        listing_payments.filter(status=FarmerMarketListingPayment.StatusChoices.PAID).aggregate(
            total=Sum("field_officer_commission_amount")
        ).get("total")
    )
    commission_paid = _int(
        FarmerMarketCommissionPayout.objects.filter(payment__listing__field_officer=user).aggregate(total=Sum("amount_paid")).get("total")
    )
    open_assigned_orders = assigned_orders.exclude(
        order_status__in=[
            MarketSellerOrder.OrderStatus.DELIVERED,
            MarketSellerOrder.OrderStatus.CANCELLED,
        ]
    ).count()
    awaiting_fee = listings.filter(status=FarmerMarketListing.Status.AWAITING_PAYMENT).count()
    failed_listing_payments = listing_payments.filter(status=FarmerMarketListingPayment.StatusChoices.FAILED).count()

    listing_labels, listing_data = _status_breakdown(listings, "status", FarmerMarketListing.Status.choices)
    contract_labels, contract_data = _status_breakdown(contracts, "status", Contract.STATUS_CHOICES)
    schedule_labels = ["Pending", "Partial", "Overdue", "Paid"]
    schedule_data = [
        schedules.filter(status="PENDING").count(),
        schedules.filter(status="PARTIAL").count(),
        schedules.filter(status="OVERDUE").count(),
        schedules.filter(status="PAID").count(),
    ]

    listing_series = _build_time_series(listings, date_field="created_at", days=days)
    payment_series = _build_time_series(
        listing_payments.filter(status=FarmerMarketListingPayment.StatusChoices.PAID),
        date_field="created_at",
        days=days,
        sum_field="amount_inclusive",
    )
    trend_labels, trend_datasets = _merge_series(listing_series, payment_series)

    farmer_rows = (
        User.objects.filter(id__in=assigned_farmer_ids)
        .annotate(
            contracts_total=Count("contracts", distinct=True),
            active_contracts_total=Count("contracts", filter=Q(contracts__status="ACTIVE"), distinct=True),
            overdue_schedules_total=Count("contracts__payment_schedules", filter=Q(contracts__payment_schedules__status="OVERDUE"), distinct=True),
            live_listings_total=Count("farmer_market_listings", filter=Q(farmer_market_listings__field_officer=user, farmer_market_listings__status=FarmerMarketListing.Status.LIVE), distinct=True),
            pending_listings_total=Count("farmer_market_listings", filter=Q(farmer_market_listings__field_officer=user, farmer_market_listings__status__in=[FarmerMarketListing.Status.PENDING_APPROVAL, FarmerMarketListing.Status.CHANGES_REQUESTED, FarmerMarketListing.Status.AWAITING_PAYMENT]), distinct=True),
        )
        .order_by("-overdue_schedules_total", "-pending_listings_total", "first_name", "last_name")[:6]
    )

    summary_cards = [
        _summary_card(
            "Coverage snapshot",
            f"You currently cover {len(assigned_farmer_ids)} assigned farmers across {assigned_groups} active groups.",
            "fa-people-group",
            tone="emerald",
        ),
        _summary_card(
            "Listing pressure",
            f"{pending_listing_reviews} farmer listings need review while {awaiting_fee} are still waiting for posting-fee confirmation.",
            "fa-clipboard-check",
            tone="amber",
        ),
        _summary_card(
            "Collections and support",
            f"Commission earned stands at {_currency(commission_earned)} with {_currency(max(commission_earned - commission_paid, 0))} still unpaid.",
            "fa-hand-holding-dollar",
            tone="blue",
        ),
    ]

    sections = [
        _section(
            "field-performance",
            "Field Performance",
            "Operational coverage across assigned farmers, contracts, and public farmer products.",
            cards=[
                _kpi("Assigned farmers", f"{len(assigned_farmer_ids):,}", "Farmers directly linked to you.", "fa-user-group", tone="emerald", href=safe_reverse("market:field_officer_register_farmer")),
                _kpi("Assigned groups", f"{assigned_groups:,}", "Groups that include your assigned farmers.", "fa-people-group", tone="blue", href=safe_reverse("contract_market_place:group_contract_list")),
                _kpi("Active contracts", f"{active_contracts:,}", "Assigned-farmer contracts already running.", "fa-file-circle-check", tone="emerald", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Pending signatures", f"{pending_signatures:,}", "Assigned-farmer contracts awaiting signature.", "fa-signature", tone="amber", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Overdue schedules", f"{overdue_schedules:,}", "Assigned-farmer schedules already overdue.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
                _kpi("Open assigned orders", f"{open_assigned_orders:,}", "Marketplace fulfilment tasks assigned to you.", "fa-truck-fast", tone="slate", href=safe_reverse("market:market_staff_assigned_orders")),
            ],
            charts=[
                _chart(
                    "field-listing-status",
                    "Farmer listing status",
                    "doughnut",
                    listing_labels,
                    [{"label": "Listings", "data": listing_data, "backgroundColor": CHART_COLORS["emerald"][: len(listing_labels)], "borderWidth": 0}],
                    subtitle="Current state of farmer products under your scope.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
                _chart(
                    "field-contract-status",
                    "Assigned-farmer contract pipeline",
                    "bar",
                    contract_labels,
                    [{"label": "Contracts", "data": contract_data, "backgroundColor": CHART_COLORS["blue"][: len(contract_labels)], "borderRadius": 10}],
                    subtitle="Contract stage mix across your assigned farmers.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
            ],
        ),
        _section(
            "field-collections",
            "Collections and Momentum",
            "Marketplace fee follow-up, offer activity, and commission flow.",
            cards=[
                _kpi("Live listings", f"{live_listings:,}", "Farmer products currently live on Bomabest Soko.", "fa-seedling", tone="emerald", href=safe_reverse("market:farmer_listing_approval_list")),
                _kpi("Pending reviews", f"{pending_listing_reviews:,}", "Listings waiting on your review or changes follow-up.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:farmer_listing_approval_list")),
                _kpi("Awaiting fee", f"{awaiting_fee:,}", "Listings paused until posting fee is cleared.", "fa-money-bill-wave", tone="rose", href=safe_reverse("market:farmer_listing_approval_list")),
                _kpi("Open offers", f"{active_offers:,}", "Buyer offers still awaiting action.", "fa-comments-dollar", tone="blue", href=safe_reverse("market:farmer_listing_approval_list")),
                _kpi("Commission earned", _currency(commission_earned), "Paid listing commission accrued to your portfolio.", "fa-hand-holding-dollar", tone="emerald", href=safe_reverse("market:farmer_listing_approval_list")),
                _kpi("Commission paid", _currency(commission_paid), "Recorded commission payouts already settled.", "fa-wallet", tone="slate", href=safe_reverse("market:farmer_listing_approval_list")),
            ],
            charts=[
                _chart(
                    "field-activity-trend",
                    "Listing and fee activity trend",
                    "line",
                    trend_labels,
                    [
                        {
                            "label": "Listings created",
                            "data": trend_datasets[0],
                            "borderColor": CHART_COLORS["emerald"][0],
                            "backgroundColor": "rgba(34, 197, 94, 0.12)",
                            "tension": 0.35,
                        },
                        {
                            "label": "Paid listing fees (KES)",
                            "data": trend_datasets[1],
                            "borderColor": CHART_COLORS["amber"][0],
                            "backgroundColor": "rgba(245, 158, 11, 0.12)",
                            "tension": 0.35,
                        },
                    ],
                    subtitle="Selected reporting window for listing creation and fee collections.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
                _chart(
                    "field-schedule-status",
                    "Assigned payment schedule status",
                    "bar",
                    schedule_labels,
                    [{"label": "Schedules", "data": schedule_data, "backgroundColor": CHART_COLORS["mixed"][: len(schedule_labels)], "borderRadius": 10}],
                    subtitle="Payment pressure across assigned farmers.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
            ],
            highlights=[
                f"{sold_listings} assigned-farmer listings have already been marked sold.",
                f"{failed_listing_payments} listing payment attempts are currently recorded as failed.",
            ],
        ),
        _section(
            "field-focus",
            "Farmers Needing Attention",
            "Farmers ordered by overdue pressure and listing follow-up needs.",
            tables=[
                _table(
                    "Assigned farmers",
                    ["Farmer", "Contracts", "Active", "Overdue", "Listings"],
                    [
                        {
                            "values": [
                                row.get_full_name() or row.phone_number or f"Farmer {row.id}",
                                f"{_int(row.contracts_total):,}",
                                f"{_int(row.active_contracts_total):,}",
                                f"{_int(row.overdue_schedules_total):,}",
                                f"{_int(row.live_listings_total):,} live / {_int(row.pending_listings_total):,} pending",
                            ]
                        }
                        for row in farmer_rows
                    ],
                    subtitle="Use this table to decide where to intervene first.",
                    empty="No assigned farmers found yet.",
                )
            ],
        ),
    ]

    return {
        "kpis": [
            _kpi("Assigned farmers", f"{len(assigned_farmer_ids):,}", "Farmers linked to your field portfolio.", "fa-user-group", tone="emerald", href=safe_reverse("market:field_officer_register_farmer")),
            _kpi("Pending reviews", f"{pending_listing_reviews:,}", "Listings needing review or change management.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:farmer_listing_approval_list")),
            _kpi("Live listings", f"{live_listings:,}", "Farmer products already visible on Bomabest Soko.", "fa-seedling", tone="blue", href=safe_reverse("market:farmer_listing_approval_list")),
            _kpi("Overdue schedules", f"{overdue_schedules:,}", "Assigned-farmer payment schedules overdue.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
            _kpi("Commission earned", _currency(commission_earned), "Fee commission earned from paid farmer listings.", "fa-hand-holding-dollar", tone="emerald", href=safe_reverse("market:farmer_listing_approval_list")),
            _kpi("Open assigned orders", f"{open_assigned_orders:,}", "Marketplace fulfilment tasks assigned to you.", "fa-truck-fast", tone="slate", href=safe_reverse("market:market_staff_assigned_orders")),
        ],
        "alerts": [
            _kpi("Awaiting posting fee", f"{awaiting_fee:,}", "Listings blocked until payment clears.", "fa-money-bill-wave", tone="amber", href=safe_reverse("market:farmer_listing_approval_list")),
            _kpi("Failed listing payments", f"{failed_listing_payments:,}", "Listing payment attempts that failed and need follow-up.", "fa-circle-xmark", tone="rose", href=safe_reverse("market:farmer_listing_approval_list")),
            _kpi("Open buyer offers", f"{active_offers:,}", "Buyer offers that still need field follow-through.", "fa-comments-dollar", tone="blue", href=safe_reverse("market:farmer_listing_approval_list")),
        ],
        "summary_cards": summary_cards,
        "sections": sections,
        "activity": _build_recent_activity(user),
    }


def _build_farmer_reports(user, days: int) -> dict:
    contracts = Contract.objects.filter(farmer=user)
    schedules = PaymentSchedule.objects.filter(contract__farmer=user)
    payments = Payment.objects.filter(farmer=user)
    group_contracts = GroupContract.objects.filter(
        group__memberships__user=user,
        group__memberships__is_active=True,
    ).distinct()
    listings = FarmerMarketListing.objects.filter(farmer=user)
    offers = FarmerMarketListingOffer.objects.filter(listing__farmer=user)
    assignment = (
        FieldOfficerAssignment.objects.select_related("field_officer").filter(farmer=user).order_by("-id").first()
    )
    officer = getattr(assignment, "field_officer", None)

    active_contracts = contracts.filter(status="ACTIVE").count()
    pending_contracts = contracts.filter(status="DRAFT").count()
    pending_signatures = contracts.filter(status="PENDING_SIGN").count()
    overdue_schedules = schedules.filter(status="OVERDUE").count()
    total_paid = _int(payments.filter(status="COMPLETED").aggregate(total=Sum("amount")).get("total"))
    remaining_balance = _int(schedules.exclude(status="PAID").aggregate(total=Sum("balance")).get("total"))
    live_listings = listings.filter(status=FarmerMarketListing.Status.LIVE).count()
    pending_listings = listings.filter(
        status__in=[
            FarmerMarketListing.Status.PENDING_APPROVAL,
            FarmerMarketListing.Status.CHANGES_REQUESTED,
            FarmerMarketListing.Status.AWAITING_PAYMENT,
            FarmerMarketListing.Status.DRAFT,
        ]
    ).count()
    sold_listings = listings.filter(status=FarmerMarketListing.Status.SOLD).count()
    open_offers = offers.filter(status=FarmerMarketListingOffer.Status.PENDING).count()
    group_memberships = FarmerGroup.objects.filter(memberships__user=user, memberships__is_active=True).distinct().count()
    pending_group_signatures = group_contracts.filter(
        Q(chairperson=user, chair_signed=False)
        | Q(secretary=user, secretary_signed=False)
        | Q(treasurer=user, treasurer_signed=False),
        status__in=["APPROVED", "PARTIALLY_SIGNED"],
    ).count()

    contract_labels, contract_data = _status_breakdown(contracts, "status", Contract.STATUS_CHOICES)
    schedule_labels = ["Pending", "Partial", "Overdue", "Paid"]
    schedule_data = [
        schedules.filter(status="PENDING").count(),
        schedules.filter(status="PARTIAL").count(),
        schedules.filter(status="OVERDUE").count(),
        schedules.filter(status="PAID").count(),
    ]
    listing_labels, listing_data = _status_breakdown(listings, "status", FarmerMarketListing.Status.choices)
    payment_series = _build_time_series(
        payments.filter(status="COMPLETED"),
        date_field="created_at",
        days=days,
        sum_field="amount",
    )

    upcoming_schedules = schedules.exclude(status="PAID").order_by("due_date")[:6]
    recent_contracts = contracts.order_by("-created_at")[:6]
    recent_offers = offers.select_related("listing", "buyer").order_by("-updated_at")[:6]

    summary_cards = [
        _summary_card(
            "Next step",
            "Focus first on overdue schedules and any contracts waiting for your signature so they do not stall.",
            "fa-compass-drafting",
            tone="emerald",
        ),
        _summary_card(
            "Field support",
            f"Your assigned field officer is {officer.get_full_name() if officer else 'not yet assigned'}{f' ({officer.phone_number})' if officer and officer.phone_number else ''}.",
            "fa-user-tie",
            tone="blue",
        ),
        _summary_card(
            "Marketplace visibility",
            f"You currently have {live_listings} live listing(s), {pending_listings} listing(s) needing action, and {open_offers} open buyer offer(s).",
            "fa-store",
            tone="amber",
        ),
    ]

    sections = [
        _section(
            "farmer-contracts",
            "Contracts and Payments",
            "A simple view of your contract movement, balances, and payment pressure.",
            cards=[
                _kpi("Active contracts", f"{active_contracts:,}", "Contracts already running.", "fa-file-circle-check", tone="emerald", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Pending requests", f"{pending_contracts:,}", "Contracts still in draft or approval stages.", "fa-file-circle-plus", tone="amber", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Need signature", f"{pending_signatures:,}", "Contracts waiting for your signature.", "fa-signature", tone="blue", href=safe_reverse("contract_market_place:contract_list")),
                _kpi("Overdue payments", f"{overdue_schedules:,}", "Schedules already overdue.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
                _kpi("Total paid", _currency(total_paid), "Completed payments made so far.", "fa-money-bill-wave", tone="emerald", href=safe_reverse("payments:farmer_payment_list")),
                _kpi("Remaining balance", _currency(remaining_balance), "Outstanding balance still open.", "fa-scale-balanced", tone="slate", href=safe_reverse("payments:farmer_payment_list")),
            ],
            charts=[
                _chart(
                    "farmer-contract-status",
                    "My contract status",
                    "doughnut",
                    contract_labels,
                    [{"label": "Contracts", "data": contract_data, "backgroundColor": CHART_COLORS["emerald"][: len(contract_labels)], "borderWidth": 0}],
                    subtitle="Status mix for your individual contracts.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
                _chart(
                    "farmer-payment-status",
                    "My payment schedule status",
                    "bar",
                    schedule_labels,
                    [{"label": "Schedules", "data": schedule_data, "backgroundColor": CHART_COLORS["amber"][: len(schedule_labels)], "borderRadius": 10}],
                    subtitle="A quick look at schedule pressure.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
                _chart(
                    "farmer-payment-trend",
                    "Payment trend",
                    "line",
                    [label for _bucket, label, _value in payment_series["points"]],
                    [
                        {
                            "label": "Completed payments (KES)",
                            "data": [value for _bucket, _label, value in payment_series["points"]],
                            "borderColor": CHART_COLORS["blue"][0],
                            "backgroundColor": "rgba(59, 130, 246, 0.12)",
                            "tension": 0.35,
                        }
                    ],
                    subtitle="Completed payment value over the selected reporting window.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
            ],
        ),
        _section(
            "farmer-marketplace",
            "Marketplace and Group Support",
            "Buyer interest, listing progress, and farmer-group visibility in one place.",
            cards=[
                _kpi("Live listings", f"{live_listings:,}", "Products currently live on Bomabest Soko.", "fa-seedling", tone="emerald", href=safe_reverse("market:catalog_list")),
                _kpi("Listings needing action", f"{pending_listings:,}", "Draft, review, or fee follow-up items.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:catalog_list")),
                _kpi("Sold listings", f"{sold_listings:,}", "Listings already marked sold.", "fa-basket-shopping", tone="blue", href=safe_reverse("market:catalog_list")),
                _kpi("Open buyer offers", f"{open_offers:,}", "Buyer offers still waiting for a response.", "fa-comments-dollar", tone="emerald", href=safe_reverse("market:catalog_list")),
                _kpi("Group memberships", f"{group_memberships:,}", "Farmer groups you belong to.", "fa-people-group", tone="slate", href=safe_reverse("contract_market_place:my_groups")),
                _kpi("Group signatures pending", f"{pending_group_signatures:,}", "Group contracts waiting for your signature.", "fa-file-signature", tone="rose", href=safe_reverse("contract_market_place:group_contract_list")),
            ],
            charts=[
                _chart(
                    "farmer-listing-status",
                    "My listing status",
                    "doughnut",
                    listing_labels,
                    [{"label": "Listings", "data": listing_data, "backgroundColor": CHART_COLORS["mixed"][: len(listing_labels)], "borderWidth": 0}],
                    subtitle="Where your public farmer products currently stand.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
            ],
            highlights=[
                "Use the marketplace to stay visible to buyers, but keep contracts and payments moving inside the same account.",
                "If a listing is awaiting payment or changes, clear it early so it can go live faster.",
            ],
        ),
        _section(
            "farmer-upcoming",
            "Upcoming Actions",
            "Your next due items, latest contracts, and buyer interest.",
            tables=[
                _table(
                    "Upcoming payment schedules",
                    ["Due date", "Installment", "Status", "Balance"],
                    [
                        {
                            "values": [
                                schedule.due_date.strftime("%d %b %Y"),
                                f"#{schedule.installment_number}",
                                schedule.get_status_display(),
                                _currency(schedule.balance),
                            ]
                        }
                        for schedule in upcoming_schedules
                    ],
                    subtitle="Nearest unpaid schedules first.",
                    empty="No unpaid schedules at the moment.",
                ),
                _table(
                    "Recent contracts",
                    ["Contract", "Type", "Status", "Amount"],
                    [
                        {
                            "values": [
                                f"#{contract.id}",
                                contract.get_type_display(),
                                contract.get_status_display(),
                                _currency(contract.total_amount),
                            ],
                            "url": safe_reverse("contract_market_place:contract_detail", args=[contract.id]),
                        }
                        for contract in recent_contracts
                    ],
                    subtitle="Your latest personal contract records.",
                    empty="No contracts found yet.",
                ),
                _table(
                    "Recent buyer offers",
                    ["Listing", "Buyer", "Status", "Offer total"],
                    [
                        {
                            "values": [
                                offer.listing.name,
                                offer.buyer.get_full_name() or offer.buyer.phone_number or "Buyer",
                                offer.get_status_display(),
                                _currency(offer.offer_total_amount),
                            ],
                            "url": safe_reverse("market:farmer_listing_detail", kwargs={"slug": offer.listing.slug}),
                        }
                        for offer in recent_offers
                    ],
                    subtitle="Latest buyer movement on your listings.",
                    empty="No buyer offers yet.",
                ),
            ],
        ),
    ]

    return {
        "kpis": [
            _kpi("Active contracts", f"{active_contracts:,}", "Contracts already active.", "fa-file-circle-check", tone="emerald", href=safe_reverse("contract_market_place:contract_list")),
            _kpi("Need signature", f"{pending_signatures:,}", "Contracts still waiting on you.", "fa-signature", tone="amber", href=safe_reverse("contract_market_place:contract_list")),
            _kpi("Overdue schedules", f"{overdue_schedules:,}", "Schedules already overdue.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
            _kpi("Live listings", f"{live_listings:,}", "Farmer products currently live.", "fa-seedling", tone="emerald", href=safe_reverse("market:catalog_list")),
            _kpi("Open buyer offers", f"{open_offers:,}", "Buyer offers waiting for movement.", "fa-comments-dollar", tone="blue", href=safe_reverse("market:catalog_list")),
            _kpi("Remaining balance", _currency(remaining_balance), "Outstanding balance still open.", "fa-scale-balanced", tone="slate", href=safe_reverse("payments:farmer_payment_list")),
        ],
        "alerts": [
            _kpi("Payments overdue", f"{overdue_schedules:,}", "Prioritize these to keep your contracts healthy.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
            _kpi("Listings needing action", f"{pending_listings:,}", "Listings that still need review, edits, or posting fees.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:catalog_list")),
            _kpi("Group signatures", f"{pending_group_signatures:,}", "Group contracts still waiting for your signature.", "fa-people-group", tone="blue", href=safe_reverse("contract_market_place:group_contract_list")),
        ],
        "summary_cards": summary_cards,
        "sections": sections,
        "activity": _build_recent_activity(user),
    }


def _build_seller_reports(user, days: int, seller_profile: SellerProfile | None) -> dict:
    has_seller_profile = seller_profile is not None
    is_approved = bool(seller_profile and seller_profile.status == SellerProfile.Status.APPROVED)
    products = MarketProduct.objects.filter(seller=seller_profile) if seller_profile else MarketProduct.objects.none()
    seller_orders = MarketSellerOrder.objects.filter(seller=seller_profile) if seller_profile else MarketSellerOrder.objects.none()
    paid_seller_orders = seller_orders.filter(parent_order__payment_status=MarketOrder.PaymentStatus.PAID)
    buyer_orders_count = MarketOrder.objects.filter(buyer=user).count()

    approved_products = products.filter(status=MarketProduct.Status.APPROVED, is_active=True).count()
    pending_products = products.filter(status=MarketProduct.Status.PENDING_APPROVAL).count()
    rejected_products = products.filter(status=MarketProduct.Status.REJECTED).count()
    draft_products = products.filter(status=MarketProduct.Status.DRAFT).count()
    open_orders = seller_orders.exclude(
        order_status__in=[
            MarketSellerOrder.OrderStatus.DELIVERED,
            MarketSellerOrder.OrderStatus.CANCELLED,
        ]
    ).count()
    completed_orders = seller_orders.filter(order_status=MarketSellerOrder.OrderStatus.DELIVERED).count()
    paid_order_value = _int(paid_seller_orders.aggregate(total=Sum("subtotal_amount")).get("total"))
    payout_placeholder = _int(paid_seller_orders.aggregate(total=Sum("seller_net_amount_placeholder")).get("total"))

    product_labels, product_data = _status_breakdown(products, "status", MarketProduct.Status.choices)
    order_labels, order_data = _status_breakdown(seller_orders, "order_status", MarketSellerOrder.OrderStatus.choices)
    orders_series = _build_time_series(seller_orders, date_field="created_at", days=days)
    value_series = _build_time_series(paid_seller_orders, date_field="created_at", days=days, sum_field="subtotal_amount")
    trend_labels, trend_datasets = _merge_series(orders_series, value_series)

    top_products = list(
        MarketOrderItem.objects.filter(seller_order__seller=seller_profile)
        .values("product_name_snapshot")
        .annotate(lines_sold=Count("id"), subtotal_value=Coalesce(Sum("line_subtotal"), Value(0), output_field=IntegerField()))
        .order_by("-lines_sold", "-subtotal_value")[:5]
    ) if seller_profile else []
    recent_seller_orders = list(
        seller_orders.select_related("parent_order").order_by("-created_at")[:6]
    )

    seller_state_text = "Not started"
    if seller_profile:
        seller_state_text = seller_profile.get_status_display()

    summary_cards = [
        _summary_card(
            "Seller readiness",
            (
                "Your seller account is fully approved and ready for product operations."
                if is_approved
                else "Complete or monitor your seller application to unlock product management."
            ),
            "fa-store",
            tone="emerald" if is_approved else "amber",
        ),
        _summary_card(
            "Marketplace movement",
            f"You currently have {approved_products} approved product(s), {pending_products} pending product(s), and {open_orders} active seller order(s).",
            "fa-chart-line",
            tone="blue",
        ),
        _summary_card(
            "Hybrid account note",
            f"This account still has {buyer_orders_count} buyer order(s) on record, but seller operations remain the focus inside the internal dashboard.",
            "fa-user-gear",
            tone="slate",
        ),
    ]

    sections = [
        _section(
            "seller-operations",
            "Seller Operations",
            "Product readiness, order movement, and storefront execution from the unified internal platform.",
            cards=[
                _kpi("Seller status", seller_state_text, "Current seller profile status.", "fa-id-card", tone="amber", href=safe_reverse("market:seller_status")),
                _kpi("Approved products", f"{approved_products:,}", "Products currently live or ready to sell.", "fa-box-open", tone="emerald", href=safe_reverse("market:seller_product_list")),
                _kpi("Pending products", f"{pending_products:,}", "Products waiting for moderation.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:seller_product_list")),
                _kpi("Rejected products", f"{rejected_products:,}", "Products needing revision before resubmission.", "fa-circle-xmark", tone="rose", href=safe_reverse("market:seller_product_list")),
                _kpi("Draft products", f"{draft_products:,}", "Unsubmitted seller drafts.", "fa-pen-ruler", tone="slate", href=safe_reverse("market:seller_product_list")),
                _kpi("Open seller orders", f"{open_orders:,}", "Seller orders still in motion.", "fa-truck-fast", tone="blue", href=safe_reverse("market:seller_product_list")),
                _kpi("Completed orders", f"{completed_orders:,}", "Orders already delivered.", "fa-circle-check", tone="emerald", href=safe_reverse("market:seller_product_list")),
                _kpi("Paid order value", _currency(paid_order_value), "Subtotal value from paid seller orders.", "fa-money-bill-trend-up", tone="emerald", href=safe_reverse("market:seller_product_list")),
                _kpi("Net placeholder", _currency(payout_placeholder), "Current seller net placeholder from paid orders.", "fa-wallet", tone="slate", href=safe_reverse("market:seller_product_list")),
            ],
            charts=[
                _chart(
                    "seller-product-status",
                    "Product status mix",
                    "doughnut",
                    product_labels,
                    [{"label": "Products", "data": product_data, "backgroundColor": CHART_COLORS["mixed"][: len(product_labels)], "borderWidth": 0}],
                    subtitle="Current state of your marketplace products.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
                _chart(
                    "seller-order-status",
                    "Seller order pipeline",
                    "bar",
                    order_labels,
                    [{"label": "Orders", "data": order_data, "backgroundColor": CHART_COLORS["blue"][: len(order_labels)], "borderRadius": 10}],
                    subtitle="Status mix for orders tied to your products.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"display": False}}},
                ),
                _chart(
                    "seller-order-trend",
                    "Orders and paid value trend",
                    "line",
                    trend_labels,
                    [
                        {
                            "label": "Seller orders",
                            "data": trend_datasets[0],
                            "borderColor": CHART_COLORS["blue"][0],
                            "backgroundColor": "rgba(59, 130, 246, 0.12)",
                            "tension": 0.35,
                        },
                        {
                            "label": "Paid subtotal value (KES)",
                            "data": trend_datasets[1],
                            "borderColor": CHART_COLORS["emerald"][0],
                            "backgroundColor": "rgba(34, 197, 94, 0.12)",
                            "tension": 0.35,
                        },
                    ],
                    subtitle="Selected window for seller order volume and paid subtotal value.",
                    options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                ),
            ],
        ),
        _section(
            "seller-drilldowns",
            "Seller Drill-Downs",
            "Top-performing products and recent buyer order movement.",
            tables=[
                _table(
                    "Top products",
                    ["Product", "Order lines", "Subtotal value"],
                    [
                        {
                            "values": [
                                row["product_name_snapshot"] or "Product",
                                f"{_int(row['lines_sold']):,}",
                                _currency(row["subtotal_value"]),
                            ]
                        }
                        for row in top_products
                    ],
                    subtitle="Products getting the most order-line activity.",
                    empty="No product order activity recorded yet.",
                ),
                _table(
                    "Recent seller orders",
                    ["Order", "Status", "Fulfilment", "Subtotal"],
                    [
                        {
                            "values": [
                                seller_order.parent_order.order_number or f"Order {seller_order.id}",
                                seller_order.get_order_status_display(),
                                seller_order.get_fulfillment_status_display(),
                                _currency(seller_order.subtotal_amount),
                            ]
                        }
                        for seller_order in recent_seller_orders
                    ],
                    subtitle="Most recent seller suborders tied to your account.",
                    empty="No seller orders recorded yet.",
                ),
            ],
            highlights=[
                "If your seller profile is pending or rejected, use the status page first before expecting product drafts to move live.",
                "Seller operations stay inside the unified internal dashboard, while buyer flows remain marketplace-facing.",
            ],
        ),
    ]

    alerts = [
        _kpi("Seller approval", seller_state_text, "Seller profile readiness for marketplace operations.", "fa-id-card", tone="amber", href=safe_reverse("market:seller_status")),
        _kpi("Products pending", f"{pending_products:,}", "Products still waiting in moderation.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:seller_product_list")),
        _kpi("Rejected products", f"{rejected_products:,}", "Products that need revision and resubmission.", "fa-circle-xmark", tone="rose", href=safe_reverse("market:seller_product_list")),
    ]

    return {
        "kpis": [
            _kpi("Seller status", seller_state_text, "Current seller profile status.", "fa-id-card", tone="amber", href=safe_reverse("market:seller_status")),
            _kpi("Approved products", f"{approved_products:,}", "Products currently approved.", "fa-box-open", tone="emerald", href=safe_reverse("market:seller_product_list")),
            _kpi("Pending products", f"{pending_products:,}", "Products waiting for moderation.", "fa-clipboard-check", tone="blue", href=safe_reverse("market:seller_product_list")),
            _kpi("Open seller orders", f"{open_orders:,}", "Seller orders still active.", "fa-truck-fast", tone="slate", href=safe_reverse("market:seller_product_list")),
            _kpi("Paid order value", _currency(paid_order_value), "Subtotal from paid seller orders.", "fa-money-bill-trend-up", tone="emerald", href=safe_reverse("market:seller_product_list")),
            _kpi("Buyer orders", f"{buyer_orders_count:,}", "Buyer orders also tied to this account.", "fa-bag-shopping", tone="slate", href=safe_reverse("market:buyer_orders")),
        ],
        "alerts": alerts,
        "summary_cards": summary_cards,
        "sections": sections,
        "activity": _build_recent_activity(user),
    }


def _build_company_reports(user, days: int, company_profile: CompanyProfile | None) -> dict:
    has_company_profile = company_profile is not None
    is_approved = bool(company_profile and company_profile.status == CompanyProfile.Status.APPROVED)
    members = company_profile.members.select_related("user") if company_profile else CompanyMember.objects.none()
    invitations = company_profile.invitations.all() if company_profile else CompanyInvitation.objects.none()
    products = company_profile.products.all() if company_profile else MarketProduct.objects.none()

    active_members = members.filter(is_active=True).count()
    owner_members = members.filter(member_role=CompanyMember.Roles.OWNER).count()
    pending_invites = invitations.filter(status=CompanyInvitation.Status.PENDING).count()
    approved_products = products.filter(status=MarketProduct.Status.APPROVED, is_active=True).count()
    pending_products = products.filter(status=MarketProduct.Status.PENDING_APPROVAL).count()
    draft_products = products.filter(status=MarketProduct.Status.DRAFT).count()

    summary_cards = [
        _summary_card(
            "Company readiness",
            (
                "Your company profile is approved and ready for product operations."
                if is_approved
                else "Complete or monitor your company profile to unlock company product operations."
            ),
            "fa-building",
            tone="emerald" if is_approved else "amber",
        ),
        _summary_card(
            "Team movement",
            f"You currently have {active_members} active member(s), {pending_invites} pending invite(s), and {owner_members} owner role(s).",
            "fa-people-group",
            tone="blue",
        ),
        _summary_card(
            "Company pipeline",
            f"Product lifecycle counts: {approved_products} approved, {pending_products} pending, and {draft_products} draft.",
            "fa-boxes-stacked",
            tone="slate",
        ),
    ]

    sections = [
        _section(
            "company-operations",
            "Company Operations",
            "Company profile readiness, staff delegation, and product flow from the unified internal platform.",
            cards=[
                _kpi("Company status", company_profile.get_status_display() if company_profile else "Not started", "Current company profile status.", "fa-id-card", tone="amber", href=safe_reverse("market:company_workspace")),
                _kpi("Active members", f"{active_members:,}", "Salespeople and managers currently active.", "fa-users", tone="emerald", href=safe_reverse("market:company_workspace")),
                _kpi("Pending invites", f"{pending_invites:,}", "Invitations waiting for a response.", "fa-envelope", tone="blue", href=safe_reverse("market:company_workspace")),
                _kpi("Approved products", f"{approved_products:,}", "Products currently approved for the company.", "fa-box-open", tone="emerald", href=safe_reverse("market:company_workspace")),
                _kpi("Pending products", f"{pending_products:,}", "Products waiting in review.", "fa-clipboard-check", tone="amber", href=safe_reverse("market:company_workspace")),
                _kpi("Draft products", f"{draft_products:,}", "Draft company products.", "fa-pen-ruler", tone="slate", href=safe_reverse("market:company_workspace")),
            ],
            highlights=[
                "Use the company workspace to invite, deactivate, and review salespeople while the legacy farmer and field-officer flows stay unchanged.",
                "Phase one keeps company products additive, so legacy seller records continue to work until migration is complete.",
            ],
        )
    ]

    alerts = [
        _kpi("Company status", company_profile.get_status_display() if company_profile else "Not started", "Company profile readiness.", "fa-building", tone="amber", href=safe_reverse("market:company_workspace")),
        _kpi("Pending invites", f"{pending_invites:,}", "Invitations that still need attention.", "fa-envelope", tone="blue", href=safe_reverse("market:company_workspace")),
    ]

    return {
        "kpis": [
            _kpi("Company status", company_profile.get_status_display() if company_profile else "Not started", "Current company profile status.", "fa-building", tone="amber", href=safe_reverse("market:company_workspace")),
            _kpi("Active members", f"{active_members:,}", "Active company team members.", "fa-users", tone="emerald", href=safe_reverse("market:company_workspace")),
            _kpi("Pending invites", f"{pending_invites:,}", "Invites waiting on response.", "fa-envelope", tone="blue", href=safe_reverse("market:company_workspace")),
            _kpi("Approved products", f"{approved_products:,}", "Company products currently approved.", "fa-box-open", tone="emerald", href=safe_reverse("market:company_workspace")),
        ],
        "alerts": alerts,
        "summary_cards": summary_cards,
        "sections": sections,
        "activity": _build_recent_activity(user),
    }


def _build_operations_reports(user, days: int) -> dict:
    total_contracts = Contract.objects.count()
    overdue_schedules = PaymentSchedule.objects.filter(status="OVERDUE").count()
    recent_contracts = Contract.objects.select_related("farmer").order_by("-created_at")[:5]
    contract_labels, contract_data = _status_breakdown(Contract.objects.all(), "status", Contract.STATUS_CHOICES)
    notifications_count = AppNotification.objects.filter(recipient=user, is_hidden=False, is_read=False).count()
    public_listings = FarmerMarketListing.objects.filter(status=FarmerMarketListing.Status.LIVE).count()
    public_products = MarketProduct.objects.filter(status=MarketProduct.Status.APPROVED, is_active=True).count()

    return {
        "kpis": [
            _kpi("Contracts in system", f"{total_contracts:,}", "Platform-wide contracts currently recorded.", "fa-file-contract", tone="emerald", href=safe_reverse("contract_market_place:contract_list")),
            _kpi("Overdue schedules", f"{overdue_schedules:,}", "Schedules requiring payment follow-up.", "fa-triangle-exclamation", tone="rose", href=safe_reverse("payments:farmer_payment_list")),
            _kpi("Unread notifications", f"{notifications_count:,}", "Your unread operational notifications.", "fa-bell", tone="blue", href=safe_reverse("contract_market_place:notifications_center")),
            _kpi("Live public listings", f"{public_listings:,}", "Farmer listings already visible publicly.", "fa-seedling", tone="emerald", href=safe_reverse("market:catalog_list")),
            _kpi("Approved products", f"{public_products:,}", "Approved public marketplace products.", "fa-store", tone="slate", href=safe_reverse("market:catalog_list")),
        ],
        "alerts": [
            _kpi("Unread notifications", f"{notifications_count:,}", "Open your notification center for next actions.", "fa-bell", tone="amber", href=safe_reverse("contract_market_place:notifications_center")),
        ],
        "summary_cards": [
            _summary_card(
                "Permission-based workspace",
                "This account can open the unified dashboard, but every widget and drill-down still follows the existing permission system.",
                "fa-shield-halved",
                tone="emerald",
            )
        ],
        "sections": [
            _section(
                "operations-overview",
                "Operations Overview",
                "A conservative internal view for permission-based dashboard accounts.",
                charts=[
                    _chart(
                        "operations-contract-status",
                        "Contract status mix",
                        "doughnut",
                        contract_labels,
                        [{"label": "Contracts", "data": contract_data, "backgroundColor": CHART_COLORS["mixed"][: len(contract_labels)], "borderWidth": 0}],
                        subtitle="Status mix for existing contracts.",
                        options={"responsive": True, "maintainAspectRatio": False, "plugins": {"legend": {"position": "bottom"}}},
                    ),
                ],
                tables=[
                    _table(
                        "Recent contracts",
                        ["Contract", "Farmer", "Status", "Amount"],
                        [
                            {
                                "values": [
                                    f"#{contract.id}",
                                    contract.farmer.get_full_name() or contract.farmer.phone_number or "Farmer",
                                    contract.get_status_display(),
                                    _currency(contract.total_amount),
                                ],
                                "url": safe_reverse("contract_market_place:contract_detail", args=[contract.id]),
                            }
                            for contract in recent_contracts
                        ],
                        subtitle="Latest contract records visible in the platform.",
                        empty="No contracts recorded yet.",
                    ),
                ],
            )
        ],
        "activity": _build_recent_activity(user),
    }


def build_dashboard_reports(
    user,
    profile: str,
    *,
    days: int,
    seller_profile: SellerProfile | None = None,
    company_profile: CompanyProfile | None = None,
) -> dict:
    if profile == "admin":
        return _build_admin_reports(user, days)
    if profile == "field_officer":
        return _build_field_officer_reports(user, days)
    if profile == "farmer":
        return _build_farmer_reports(user, days)
    if profile == "seller":
        return _build_seller_reports(user, days, seller_profile)
    if profile == "company":
        return _build_company_reports(user, days, company_profile)
    return _build_operations_reports(user, days)
