"""Upload routes for file handling."""

from flask import Blueprint, flash, g, jsonify, make_response, redirect, render_template, request, url_for

from words_to_readlang.parsers import list_parsers

from ..database import db
from ..models import Upload
from ..services import UploadService

upload_bp = Blueprint("upload", __name__)


@upload_bp.route("/")
def upload_form():
    """Display file upload form."""
    available_parsers = list_parsers()
    return render_template("upload.html", parsers=available_parsers)


@upload_bp.route("/", methods=["POST"])
def upload_file():
    """Handle file upload and parsing."""
    # Check if file was uploaded
    if "file" not in request.files:
        flash("No file uploaded", "error")
        return redirect(url_for("upload.upload_form"))

    file = request.files["file"]

    if file.filename == "":
        flash("No file selected", "error")
        return redirect(url_for("upload.upload_form"))

    # Create session if it doesn't exist yet
    if not g.session:
        from ..services import SessionService
        session = SessionService.create_session()
        db.session.add(session)
        db.session.commit()
        g.session = session
        g.new_session = True

    # Get format selection
    format_name = request.form.get("format")
    auto_detect = request.form.get("auto_detect") == "on"

    # Get language selection
    source_language = request.form.get("source_language", "fin")
    target_language = request.form.get("target_language", "eng")

    try:
        # Process upload
        upload = UploadService.process_upload(
            file=file,
            session_id=g.session.id,
            format_name=format_name if not auto_detect else None,
            auto_detect=auto_detect,
            source_language=source_language,
            target_language=target_language,
        )

        flash(
            f"Successfully uploaded {upload.filename} with {upload.entry_count} entries",
            "success",
        )

        # Set session cookie if this is a new session
        response = redirect(url_for("preview.preview_upload", upload_id=upload.id))
        if g.new_session:
            response.set_cookie(
                "magic_phrase",
                g.session.magic_phrase,
                max_age=30 * 24 * 60 * 60,  # 30 days
                httponly=True,
                samesite="Lax",
            )
        return response

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

    except Exception as e:
        flash(f"Error processing file: {str(e)}", "error")
        return redirect(url_for("upload.upload_form"))


@upload_bp.route("/detect-format", methods=["POST"])
def detect_format():
    """HTMX endpoint for auto-detecting file format.

    Returns JSON with detected format name or error.
    """
    if "file" not in request.files:
        return jsonify({"error": "No file provided"}), 400

    file = request.files["file"]

    if file.filename == "":
        return jsonify({"error": "No file selected"}), 400

    try:
        import tempfile
        from pathlib import Path

        # Save to temp location
        temp_dir = Path(tempfile.mkdtemp())
        temp_path = temp_dir / file.filename
        file.save(str(temp_path))

        # Detect format
        detected = UploadService.detect_format(temp_path)

        # Clean up
        temp_path.unlink()
        temp_dir.rmdir()

        if detected:
            return jsonify({"format": detected, "confidence": "high"})
        else:
            return jsonify({"format": None, "confidence": "none"})

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@upload_bp.route("/manage")
def manage_uploads():
    """Display all uploads for the session in a table view with multi-select.

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

    # Get all uploads for this session
    uploads = (
        Upload.query.filter_by(session_id=g.session.id)
        .order_by(Upload.uploaded_at.desc())
        .all()
    )

    return render_template("manage_uploads.html", uploads=uploads)


@upload_bp.route("/bulk-delete", methods=["POST"])
def bulk_delete_uploads():
    """Delete multiple uploads at once.

    Form data:
        upload_ids: List of upload IDs to delete

    Returns:
        Redirect to manage uploads page
    """
    # Require session
    if not g.session:
        flash("Please upload a file first to start a session.", "info")
        return redirect(url_for("main.index"))

    # Get selected upload IDs from form
    upload_ids = request.form.getlist("upload_ids", type=int)

    if not upload_ids:
        flash("No uploads selected for deletion.", "warning")
        return redirect(url_for("upload.manage_uploads"))

    # Verify all uploads belong to session and delete them
    uploads = Upload.query.filter(
        Upload.id.in_(upload_ids),
        Upload.session_id == g.session.id
    ).all()

    if len(uploads) != len(upload_ids):
        flash("Some uploads could not be found or don't belong to your session.", "error")
        return redirect(url_for("upload.manage_uploads"))

    # Count total entries being deleted
    total_entries = sum(upload.entry_count for upload in uploads)

    # Delete uploads (cascade deletes all entries)
    for upload in uploads:
        db.session.delete(upload)

    db.session.commit()

    flash(
        f"Deleted {len(uploads)} upload(s) with {total_entries} total entries. "
        f"Note: Entries remain in the word pool.",
        "success"
    )

    return redirect(url_for("upload.manage_uploads"))


@upload_bp.route("/<int:upload_id>", methods=["DELETE", "POST"])
def delete_upload(upload_id):
    """Delete an upload and all its entries.

    Args:
        upload_id: Upload ID to delete

    Returns:
        Redirect to home page or empty response for HTMX
    """
    # 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

    # Delete upload (cascade deletes all entries)
    db.session.delete(upload)
    db.session.commit()

    # Return success for HTMX or redirect
    if request.headers.get("HX-Request"):
        return "", 200
    return redirect(url_for("main.index"))
