"""
API routes for document scheduler management.
"""

from flask import Blueprint, jsonify, session
from loguru import logger

from ..scheduler.background import get_background_job_scheduler
from ..web.auth.decorators import login_required

# Create blueprint
scheduler_bp = Blueprint("document_scheduler", __name__)

# NOTE: Routes use session["username"] (not .get()) intentionally.
# @login_required guarantees the key exists; direct access fails fast
# if the decorator is ever removed.
# Helper functions (not decorated) keep .get() for safety.


def get_current_username():
    """Get current username from session."""
    return session.get("username")


@scheduler_bp.route("/api/scheduler/status", methods=["GET"])
@login_required
def get_scheduler_status():
    """Get the current status of the document scheduler for the current user."""
    try:
        username = get_current_username()
        if not username:
            return jsonify({"error": "User not authenticated"}), 401

        scheduler = get_background_job_scheduler()
        status = scheduler.get_document_scheduler_status(username)
        return jsonify(status)
    except Exception:
        logger.exception("Error getting scheduler status")
        return jsonify({"error": "Failed to get scheduler status"}), 500


@scheduler_bp.route("/api/scheduler/run-now", methods=["POST"])
@login_required
def trigger_manual_run():
    """Trigger a manual processing run of the document scheduler for the current user."""
    try:
        username = get_current_username()
        if not username:
            return jsonify({"error": "User not authenticated"}), 401

        scheduler = get_background_job_scheduler()
        if scheduler.trigger_document_processing(username):
            return jsonify(
                {"message": "Manual document processing triggered successfully"}
            )
        return (
            jsonify(
                {
                    "error": "Failed to trigger document processing - user may not be active or processing disabled"
                }
            ),
            400,
        )
    except Exception:
        logger.exception("Error triggering manual run")
        return jsonify({"error": "Failed to trigger manual run"}), 500
