from __future__ import annotations

from flask import Blueprint, jsonify

from backend.services.admin_config_service import read_config
from backend.services.prompts_library_service import read_prompts
from backend.utils.logger_utils import log_http_request
from backend.utils.logging_utils import get_logger

prompts_bp = Blueprint("prompts", __name__, url_prefix="/prompts")
logger = get_logger(__name__)


@prompts_bp.route("/library", methods=["GET"])
@log_http_request
def get_prompts_library_for_users():
    """
    Returns the prompts library filtered to only include enabled prompts.

    The enabled state is determined solely by the admin config override.
    Prompts are enabled by default (True) unless explicitly disabled by admin.
    """
    try:
        prompts_data, _ = read_prompts()

        admin_config, _ = read_config()

        # Get prompt overrides from admin config (stored at root level as promptsAttributesById)
        attributes_by_id = admin_config.get("promptsAttributesById") or {}

        all_prompts = prompts_data.get("prompts", [])
        enabled_prompts = []

        for prompt in all_prompts:
            prompt_id = prompt.get("id")
            if not prompt_id:
                continue
            
            # Check admin config for enabled state (defaults to True)
            attributes = attributes_by_id.get(prompt_id, {})
            is_enabled = attributes.get("enabled", True)

            if is_enabled:
                enabled_prompts.append(prompt)

        response = {"version": prompts_data.get("version", "1.0.0"), "prompts": enabled_prompts}

        return jsonify({"data": response}), 200

    except Exception as e:
        logger.error(f"Error getting prompts library for users: {e}")
        return jsonify({"error": str(e)}), 500
