"""Validation routes for entry validation."""

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

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

validate_bp = Blueprint("validate", __name__)


@validate_bp.route("/<int:upload_id>", methods=["POST"])
def validate_upload(upload_id):
    """Re-validate all entries in an upload.

    Args:
        upload_id: Upload ID to validate

    Returns:
        HTML fragments with updated validation stats and badges using HTMX OOB swaps
    """
    # Verify upload belongs to session
    upload = Upload.query.get_or_404(upload_id)

    if upload.session_id != g.session.id:
        return jsonify({"error": "Unauthorized"}), 403

    # Validate all entries
    valid, no_example, word_missing = ValidationService.validate_upload(upload_id)

    # Get all entries for badge updates
    entries = Entry.query.filter_by(upload_id=upload_id).all()

    # Return HTML fragments using Out-of-Band swaps
    return render_template(
        "htmx/validation_complete.html",
        stats={
            "valid": valid,
            "invalid_no_example": no_example,
            "invalid_word_missing": word_missing,
        },
        entries=entries,
        upload_id=upload_id,
    )


@validate_bp.route("/entry/<int:entry_id>/badge")
def get_validation_badge(entry_id):
    """HTMX endpoint for validation badge.

    Args:
        entry_id: Entry ID

    Returns:
        Rendered validation badge HTML
    """
    entry = Entry.query.get_or_404(entry_id)

    # Verify entry belongs to user's session
    if entry.upload.session_id != g.session.id:
        return "", 403

    # Revalidate entry
    ValidationService.update_entry_validation(entry)

    return render_template("components/validation_badge.html", entry=entry)
