"""Export routes for downloading CSV/ZIP files."""

from flask import Blueprint, g, redirect, send_file, url_for

from ..models import Upload
from ..services import ExportService

export_bp = Blueprint("export", __name__)


@export_bp.route("/<int:upload_id>")
def export_download(upload_id):
    """Export upload to CSV or ZIP and trigger download.

    Args:
        upload_id: Upload ID to export

    Returns:
        File download response
    """
    # Verify upload belongs to session
    upload = Upload.query.get_or_404(upload_id)

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

    try:
        # Export upload (only valid entries)
        file_path, mime_type, filename, valid_count, excluded_count = ExportService.export_upload(upload_id)

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

    except ValueError as e:
        # No entries to export
        return str(e), 400

    except Exception as e:
        # Other errors
        return f"Error exporting: {str(e)}", 500
