"""
Centralized read-only metrics for the unified internal cockpit.

Aggregations are kept single-purpose so dashboard + future API consumers can share
without duplicating query text across views (legacy market dashboard code remains
as reference; logic is consolidated here).
"""
from __future__ import annotations

from django.db.models import Count, Q, Sum

from contract.models import FieldOfficerAssignment, User
from market.models import (
    FarmerMarketListing,
    FarmerMarketListingOffer,
    FarmerMarketListingPayment,
    FarmerMarketCommissionPayout,
    MarketCategory,
    MarketOrder,
    MarketOrderItem,
    MarketProduct,
    MarketSellerOrder,
    SellerProfile,
)


def build_market_admin_cockpit_summary() -> dict:
    """Snapshot counters for marketplace administrators (no user filter)."""
    pending_sellers = SellerProfile.objects.filter(status=SellerProfile.Status.PENDING).count()
    approved_sellers = SellerProfile.objects.filter(status=SellerProfile.Status.APPROVED).count()
    pending_products = MarketProduct.objects.filter(status=MarketProduct.Status.PENDING_APPROVAL).count()
    approved_products = MarketProduct.objects.filter(
        status=MarketProduct.Status.APPROVED, is_active=True
    ).count()
    rejected_products = MarketProduct.objects.filter(status=MarketProduct.Status.REJECTED).count()
    active_categories = MarketCategory.objects.filter(is_active=True).count()
    pending_payment_orders = MarketOrder.objects.filter(
        payment_status=MarketOrder.PaymentStatus.AWAITING_PAYMENT
    ).count()
    paid_unassigned_suborders = MarketSellerOrder.objects.filter(
        parent_order__payment_status=MarketOrder.PaymentStatus.PAID,
        assigned_staff__isnull=True,
    ).count()
    farmer_pending = FarmerMarketListing.objects.filter(
        status__in=[
            FarmerMarketListing.Status.PENDING_APPROVAL,
            FarmerMarketListing.Status.CHANGES_REQUESTED,
            FarmerMarketListing.Status.AWAITING_PAYMENT,
        ]
    ).count()
    farmer_live = FarmerMarketListing.objects.filter(status=FarmerMarketListing.Status.LIVE).count()
    farmer_rejected = FarmerMarketListing.objects.filter(status=FarmerMarketListing.Status.REJECTED).count()
    paid_orders = MarketOrder.objects.exclude(paid_at__isnull=True)
    gmv_all_time = int(paid_orders.aggregate(total=Sum("grand_total")).get("total") or 0)
    top_products = list(
        MarketOrderItem.objects.filter(product__isnull=False)
        .values("product__name")
        .annotate(lines_sold=Count("id"))
        .order_by("-lines_sold")[:5]
    )
    top_categories = list(
        MarketCategory.objects.filter(is_active=True)
        .annotate(product_count=Count("products", filter=Q(products__status=MarketProduct.Status.APPROVED)))
        .order_by("-product_count", "name")[:6]
    )
    return {
        "pending_sellers": pending_sellers,
        "approved_sellers": approved_sellers,
        "pending_products": pending_products,
        "approved_products": approved_products,
        "rejected_products": rejected_products,
        "active_categories": active_categories,
        "pending_payment_orders": pending_payment_orders,
        "paid_unassigned_suborders": paid_unassigned_suborders,
        "farmer_pending_listings": farmer_pending,
        "farmer_live_listings": farmer_live,
        "farmer_rejected_listings": farmer_rejected,
        "gmv_paid_orders_kes": gmv_all_time,
        "top_products": top_products,
        "top_categories": top_categories,
    }


def build_field_officer_cockpit_summary(user) -> dict | None:
    """Operational metrics for a field officer's assigned marketplace scope."""
    if not getattr(user, "is_authenticated", False):
        return None
    if getattr(user, "type", None) != User.Types.FIELD_OFFICER:
        return None

    assigned_farmers = FieldOfficerAssignment.objects.filter(field_officer=user).count()
    listings = FarmerMarketListing.objects.filter(field_officer=user)
    listing_status_counts = dict(
        listings.values("status").annotate(c=Count("id")).values_list("status", "c")
    )
    pending_approvals = listings.filter(
        status__in=[
            FarmerMarketListing.Status.PENDING_APPROVAL,
            FarmerMarketListing.Status.CHANGES_REQUESTED,
        ]
    ).count()
    awaiting_payment = listings.filter(status=FarmerMarketListing.Status.AWAITING_PAYMENT).count()
    live_listings = listings.filter(status=FarmerMarketListing.Status.LIVE).count()
    sold_listings = listings.filter(status=FarmerMarketListing.Status.SOLD).count()

    payments_qs = FarmerMarketListingPayment.objects.filter(listing__field_officer=user)
    commission_earned = int(
        payments_qs.filter(status=FarmerMarketListingPayment.StatusChoices.PAID).aggregate(
            total=Sum("field_officer_commission_amount")
        ).get("total")
        or 0
    )
    commission_paid = int(
        FarmerMarketCommissionPayout.objects.filter(payment__listing__field_officer=user).aggregate(
            total=Sum("amount_paid")
        ).get("total")
        or 0
    )

    pending_offers = FarmerMarketListingOffer.objects.filter(
        listing__field_officer=user, status=FarmerMarketListingOffer.Status.PENDING
    ).count()

    assigned_orders = MarketSellerOrder.objects.filter(assigned_staff=user).exclude(
        order_status__in=[
            MarketSellerOrder.OrderStatus.DELIVERED,
            MarketSellerOrder.OrderStatus.CANCELLED,
        ]
    ).count()

    return {
        "assigned_farmers": assigned_farmers,
        "listing_status_counts": listing_status_counts,
        "pending_approvals": pending_approvals,
        "awaiting_payment_listings": awaiting_payment,
        "live_listings": live_listings,
        "sold_listings": sold_listings,
        "commission_earned_kes": commission_earned,
        "commission_paid_kes": commission_paid,
        "pending_offers": pending_offers,
        "open_assigned_orders": assigned_orders,
    }


def build_farmer_market_summary(user) -> dict | None:
    """Farmer-friendly marketplace operational snapshot."""
    if not getattr(user, "is_authenticated", False):
        return None
    if getattr(user, "type", None) != User.Types.FARMER:
        return None

    qs = FarmerMarketListing.objects.filter(farmer=user)
    pending = qs.filter(
        status__in=[
            FarmerMarketListing.Status.PENDING_APPROVAL,
            FarmerMarketListing.Status.CHANGES_REQUESTED,
            FarmerMarketListing.Status.AWAITING_PAYMENT,
            FarmerMarketListing.Status.DRAFT,
        ]
    ).count()
    live = qs.filter(status=FarmerMarketListing.Status.LIVE).count()
    sold = qs.filter(status=FarmerMarketListing.Status.SOLD).count()
    offers_pending = FarmerMarketListingOffer.objects.filter(
        listing__farmer=user, status=FarmerMarketListingOffer.Status.PENDING
    ).count()
    awaiting_fee = qs.filter(status=FarmerMarketListing.Status.AWAITING_PAYMENT).count()

    assignment = (
        FieldOfficerAssignment.objects.select_related("field_officer")
        .filter(farmer=user)
        .order_by("-id")
        .first()
    )
    officer = getattr(assignment, "field_officer", None)

    return {
        "my_listings_total": qs.count(),
        "pending_work": pending,
        "live_listings": live,
        "sold_listings": sold,
        "active_offers_incoming": offers_pending,
        "awaiting_hosting_fee": awaiting_fee,
        "field_officer_name": officer.get_full_name() if officer else "",
        "field_officer_phone": getattr(officer, "phone_number", "") or "" if officer else "",
    }
