import os
import platform

from django import get_version as django_version
from django.contrib.auth.decorators import login_required
from django.db.models import Count, DecimalField, ExpressionWrapper, F, Sum
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone

from .models import Order, OrderItem, Product


def home(request):
    """Render the product catalog landing page."""
    products = Product.objects.all().order_by('-created_at')
    
    context = {
        "products": products,
        "django_version": django_version(),
    }
    return render(request, "core/index.html", context)


def product_detail(request, pk):
    product = get_object_or_404(Product, pk=pk)
    return render(request, "core/product_detail.html", {"product": product})


def _is_seller(user):
    return hasattr(user, "userprofile") and user.userprofile.is_seller


@login_required
def dashboard_redirect(request):
    if _is_seller(request.user):
        return redirect("seller_dashboard")
    return redirect("buyer_dashboard")


@login_required
def buyer_dashboard(request):
    if _is_seller(request.user):
        return redirect("seller_dashboard")

    recent_orders = (
        Order.objects.filter(buyer=request.user)
        .prefetch_related("items__product")
        .order_by("-created_at")[:5]
    )
    total_orders = Order.objects.filter(buyer=request.user).count()

    context = {
        "dashboard_title": "Buyer Dashboard",
        "active_tab": "buyer",
        "recent_orders": recent_orders,
        "total_orders": total_orders,
    }
    return render(request, "core/buyer_dashboard.html", context)


@login_required
def seller_dashboard(request):
    if not _is_seller(request.user):
        return redirect("buyer_dashboard")

    seller_products = Product.objects.filter(seller=request.user)
    sales_expression = ExpressionWrapper(
        F("quantity") * F("price"), output_field=DecimalField(max_digits=12, decimal_places=2)
    )
    sales_summary = OrderItem.objects.filter(product__seller=request.user).aggregate(
        total_items=Sum("quantity"),
        total_revenue=Sum(sales_expression),
        total_orders=Count("order", distinct=True),
    )
    recent_sales = (
        OrderItem.objects.filter(product__seller=request.user)
        .select_related("product", "order__buyer")
        .order_by("-order__created_at")[:8]
    )

    context = {
        "dashboard_title": "Seller Dashboard",
        "active_tab": "seller",
        "product_count": seller_products.count(),
        "total_orders": sales_summary["total_orders"] or 0,
        "total_items": sales_summary["total_items"] or 0,
        "total_revenue": sales_summary["total_revenue"] or 0,
        "recent_sales": recent_sales,
    }
    return render(request, "core/seller_dashboard.html", context)