"""Preview routes for viewing and managing entries."""

from flask import Blueprint, g, redirect, render_template, request, url_for

from ..models import Entry, Upload
from ..services import ValidationService

preview_bp = Blueprint("preview", __name__)


@preview_bp.route("/<int:upload_id>")
def preview_upload(upload_id):
    """Display preview of upload entries with pagination.

    Args:
        upload_id: Upload ID to preview

    Returns:
        Rendered preview template
    """
    # Get upload and verify it belongs to this session
    upload = Upload.query.get_or_404(upload_id)

    if upload.session_id != g.session.id:
        return redirect(url_for("main.index"))

    # Get first page of entries
    page = request.args.get("page", 1, type=int)
    per_page = 10

    entries = (
        Entry.query.filter_by(upload_id=upload_id)
        .offset((page - 1) * per_page)
        .limit(per_page + 1)  # +1 to check if there are more
        .all()
    )

    has_more = len(entries) > per_page
    entries = entries[:per_page]  # Trim to actual page size

    # Calculate validation stats
    stats = {
        "total": upload.entry_count,
        "valid": Entry.query.filter_by(
            upload_id=upload_id, validation_status="valid"
        ).count(),
        "invalid_no_example": Entry.query.filter_by(
            upload_id=upload_id, validation_status="invalid_no_example"
        ).count(),
        "invalid_word_missing": Entry.query.filter_by(
            upload_id=upload_id, validation_status="invalid_word_missing"
        ).count(),
    }

    return render_template(
        "preview.html",
        upload=upload,
        entries=entries,
        page=page,
        has_more=has_more,
        stats=stats,
    )


@preview_bp.route("/<int:upload_id>/entries")
def get_entries(upload_id):
    """HTMX endpoint for paginated entries.

    Args:
        upload_id: Upload ID

    Returns:
        Rendered entry rows HTML fragment
    """
    # Verify upload belongs to session
    upload = Upload.query.get_or_404(upload_id)

    if upload.session_id != g.session.id:
        return "", 403

    page = request.args.get("page", 1, type=int)
    per_page = 10

    entries = (
        Entry.query.filter_by(upload_id=upload_id)
        .offset((page - 1) * per_page)
        .limit(per_page + 1)
        .all()
    )

    has_more = len(entries) > per_page
    entries = entries[:per_page]

    return render_template(
        "htmx/entry_rows.html",
        entries=entries,
        upload_id=upload_id,
        page=page + 1,
        has_more=has_more,
    )
