"""Edit routes for modifying entries."""

from flask import Blueprint, g, render_template, request

from ..database import db
from ..models import Entry
from ..services import ValidationService

edit_bp = Blueprint("edit", __name__)


@edit_bp.route("/<int:entry_id>/form")
def edit_form(entry_id):
    """HTMX endpoint for inline edit form.

    Args:
        entry_id: Entry ID to edit

    Returns:
        Rendered edit form HTML (replaces entry row)
    """
    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

    return render_template("htmx/edit_form.html", entry=entry)


@edit_bp.route("/<int:entry_id>", methods=["PUT", "POST"])
def update_entry(entry_id):
    """Save edited entry.

    Args:
        entry_id: Entry ID to update

    Returns:
        Rendered updated entry row 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

    # Update entry with edited values
    entry.edited_word = request.form.get("word", "").strip()
    entry.edited_translation = request.form.get("translation", "").strip()
    entry.edited_example = request.form.get("example", "").strip()

    # Re-validate entry
    ValidationService.update_entry_validation(entry)

    db.session.commit()

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


@edit_bp.route("/<int:entry_id>", methods=["DELETE"])
def delete_entry(entry_id):
    """Delete an entry.

    Args:
        entry_id: Entry ID to delete

    Returns:
        Empty response (removes row from DOM)
    """
    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

    # Delete entry
    db.session.delete(entry)
    db.session.commit()

    return ""
