"""Queue preview (review) view."""

from __future__ import annotations

from sqlalchemy import func
from sqlalchemy import select as sa_select
from sqlalchemy.sql import nullslast
from starlette.requests import Request
from starlette.responses import Response

from fenliu.config import settings
from fenliu.database import get_db
from fenliu.models import Post
from fenliu.models import QueueStats
from fenliu.services.api_key import get_api_key
from fenliu.services.export_eligibility import check_export_eligibility
from fenliu.templates_env import templates


async def queue_preview_page(request: Request) -> Response:
    """Render the Curated queue preview page."""
    # Get query parameters for filtering and sorting
    status_filter = request.query_params.get("status", "all").lower()
    sort_by = request.query_params.get("sort", "reviewed_at").lower()
    sort_order = request.query_params.get("order", "desc").lower()

    with get_db() as db:
        api_key = get_api_key(db)

        # Status counts across all approved posts (single GROUP BY query)
        status_counts: dict[str, int] = {
            str(row[0] or "unknown"): int(row[1])
            for row in db.execute(
                sa_select(Post.queue_status, func.count()).where(Post.approved.is_(True)).group_by(Post.queue_status)
            ).all()
        }
        pending_count = status_counts.get("pending", 0)
        reserved_count = status_counts.get("reserved", 0)
        delivered_count = status_counts.get("delivered", 0)
        error_count = status_counts.get("error", 0)

        # All-time totals from QueueStats
        stats = db.get(QueueStats, 1)
        all_time_delivered = delivered_count + (stats.total_deleted_delivered if stats else 0)
        all_time_pending = pending_count + (stats.total_deleted_pending if stats else 0)

        # Total posts matching the current filter (for pagination)
        total_filtered = status_counts.get(status_filter, 0) if status_filter != "all" else sum(status_counts.values())

        # Pagination
        page_size = settings.posts_per_page
        total_pages = max(1, (total_filtered + page_size - 1) // page_size)
        try:
            page = max(1, min(int(request.query_params.get("page", "1")), total_pages))
        except ValueError:
            page = 1
        offset = (page - 1) * page_size

        # Build filtered + sorted query, then paginate
        stmt = sa_select(Post).where(Post.approved.is_(True))
        if status_filter != "all":
            stmt = stmt.where(Post.queue_status == status_filter)

        match sort_by:
            case "spam_score":
                _sort_col = Post.spam_score
            case "author":
                _sort_col = Post.author_display_name
            case "errored_at":
                _sort_col = Post.errored_at
            case "reserved_at":
                _sort_col = Post.reserved_at
            case _:
                _sort_col = Post.reviewed_at

        _order = nullslast(_sort_col.desc() if sort_order == "desc" else _sort_col.asc())
        stmt = stmt.order_by(_order).offset(offset).limit(page_size)
        page_posts = list(db.execute(stmt).scalars().all())

        # Eligibility check only on the displayed page (not all approved posts)
        posts_data = [
            {
                "post": post,
                "queue_status": post.queue_status or "unknown",
                "eligible": (eligibility := check_export_eligibility(post, db)).eligible,
                "exclusion_reason": eligibility.reason,
                "error_reason": post.error_reason,
                "errored_at": post.errored_at,
                "reserved_at": post.reserved_at,
            }
            for post in page_posts
        ]

        context = {
            "pending_count": pending_count,
            "reserved_count": reserved_count,
            "delivered_count": delivered_count,
            "all_time_delivered": all_time_delivered,
            "all_time_pending": all_time_pending,
            "error_count": error_count,
            "posts": posts_data,
            "page": page,
            "total_pages": total_pages,
            "page_size": page_size,
            "total_filtered_count": total_filtered,
            "app_name": settings.app_name,
            "app_version": settings.app_version,
            "current_status_filter": status_filter,
            "current_sort_by": sort_by,
            "current_sort_order": sort_order,
            "api_key": api_key or "",
        }
        return templates.TemplateResponse(request, "queue_preview.html", context)
