"""Word pool routes for viewing aggregated entries across uploads."""

import tempfile
from pathlib import Path

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

from ..services import PoolService

pool_bp = Blueprint("pool", __name__)


@pool_bp.route("/")
def pool():
    """Display word pool - all entries across all uploads in session.

    Returns:
        Rendered pool template or redirect to language pair selection
    """
    # Require session
    if not g.session:
        flash("Please upload a file first to start a session.", "info")
        return redirect(url_for("main.index"))

    # Get available language pairs
    available_pairs = PoolService.get_available_language_pairs(g.session.id)

    if not available_pairs:
        flash("No uploads found. Please upload a vocabulary file first.", "info")
        return redirect(url_for("main.index"))

    # Get language pair from query params
    source_lang = request.args.get("source")
    target_lang = request.args.get("target")

    # If no language pair specified and multiple pairs exist, redirect to select
    if not (source_lang and target_lang):
        if len(available_pairs) == 1:
            # Only one pair, use it automatically
            source_lang, target_lang = available_pairs[0]
            return redirect(url_for("pool.pool", source=source_lang, target=target_lang))
        else:
            # Multiple pairs, show selection
            return render_template("pool_select.html", available_pairs=available_pairs)

    # Verify the requested pair exists
    if (source_lang, target_lang) not in available_pairs:
        flash("Invalid language pair selected.", "error")
        return redirect(url_for("pool.pool"))

    # Get first page of entries for this language pair
    page = request.args.get("page", 1, type=int)
    per_page = 50

    entries, has_more = PoolService.get_all_entries(
        g.session.id,
        source_language=source_lang,
        target_language=target_lang,
        page=page,
        per_page=per_page,
    )

    # Get validation stats for this language pair
    stats = PoolService.get_stats(g.session.id, source_language=source_lang, target_language=target_lang)

    return render_template(
        "pool.html",
        entries=entries,
        page=page,
        has_more=has_more,
        stats=stats,
        source_language=source_lang,
        target_language=target_lang,
        available_pairs=available_pairs,
    )


@pool_bp.route("/entries")
def get_entries():
    """HTMX endpoint for paginated pool entries.

    Returns:
        Rendered entry rows HTML fragment
    """
    page = request.args.get("page", 1, type=int)
    per_page = 50

    # Get language pair from query params
    source_lang = request.args.get("source")
    target_lang = request.args.get("target")

    entries, has_more = PoolService.get_all_entries(
        g.session.id,
        source_language=source_lang,
        target_language=target_lang,
        page=page,
        per_page=per_page,
    )

    return render_template(
        "htmx/pool_entry_rows.html",
        entries=entries,
        page=page + 1,
        has_more=has_more,
        source_language=source_lang,
        target_language=target_lang,
    )


@pool_bp.route("/export", methods=["POST"])
def export_pool():
    """Export selected entries from word pool.

    Form data:
        entry_ids: List of entry IDs to export (optional - if empty, exports all valid)
        source_language: Source language code
        target_language: Target language code

    Returns:
        CSV or ZIP file download
    """
    # Get selected entry IDs from form
    entry_ids = request.form.getlist("entry_ids", type=int)

    # Get language pair from form
    source_lang = request.form.get("source_language")
    target_lang = request.form.get("target_language")

    try:
        # Export entries
        file_path, mime_type, filename, exported_count, excluded_count = PoolService.export_selected(
            session_id=g.session.id,
            entry_ids=entry_ids if entry_ids else None,
            source_language=source_lang,
            target_language=target_lang,
        )

        # Show flash message about export
        if excluded_count > 0:
            flash(
                f"Exported {exported_count} valid entries. {excluded_count} invalid entries were excluded.",
                "warning",
            )
        else:
            flash(f"Exported {exported_count} entries successfully!", "success")

        # Send file
        return send_file(
            file_path,
            mimetype=mime_type,
            as_attachment=True,
            download_name=filename,
        )

    except ValueError as e:
        flash(str(e), "error")
        return redirect(url_for("pool.pool"))

    except Exception as e:
        flash(f"Error exporting entries: {str(e)}", "error")
        return redirect(url_for("pool.pool"))
