from __future__ import annotations

import dataiku
from flask import Blueprint, jsonify

from backend.services.admin_config_service import read_config
from backend.utils.dss_utils import with_impersonation
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("/collections", methods=["GET"])
@log_http_request
@with_impersonation
def get_collections_for_users():
    """
    Returns only the collections configured in promptsAssetLibraryCollectionIds.
    These are the collections that users can access in the prompt library.
    """
    try:
        admin_config = read_config()

        collection_ids = admin_config.get("promptsAssetLibraryCollectionIds") or []

        if not isinstance(collection_ids, list) or not collection_ids:
            return jsonify({"data": {"collections": []}}), 200

        client = dataiku.api_client()
        asset_library_client = client.get_enterprise_asset_library()

        # Get all collections the user has access to
        all_collections = asset_library_client.list_collections()

        # Filter to only those in the admin config
        filtered_collections = [c for c in all_collections if c.get("id") in collection_ids]

        return jsonify({"collections": filtered_collections}), 200
    except AttributeError:
        # API method not available (DSS version too old)
        logger.warning("Enterprise Asset Library API not available - DSS version may be too old")
        return jsonify({"collections": []}), 200
    except Exception as e:
        logger.exception(f"Error fetching collections for users: {e}")
        return jsonify({"error": str(e)}), 500


@prompts_bp.route("/library", methods=["GET"])
@log_http_request
@with_impersonation
def get_prompts_library_for_users():
    """
    Returns the prompts library filtered to only include enabled prompts.
    Adds isCreatedByDataiku attribute based on collectionId.
    Feeds collectionName from the collections list.
    """
    try:
        admin_config = read_config()
        client = dataiku.api_client()
        asset_library_client = client.get_enterprise_asset_library()

        prompts_attributes = admin_config.get("promptsAttributesById") or {}
        collection_ids = admin_config.get("promptsAssetLibraryCollectionIds") or []

        if not isinstance(collection_ids, list):
            collection_ids = []

        all_prompts = []

        if collection_ids:
            try:
                # Fetch prompts based on configured collection IDs
                asset_prompts = asset_library_client.list_prompts(restrict_collections=collection_ids)

                # Fetch collections to resolve names
                collections_list = asset_library_client.list_collections()
                collection_map = {c.get("id"): c.get("name") for c in collections_list}

                for p in asset_prompts:
                    if p.get("id"):
                        # Inject collectionName using the map
                        c_id = p.get("collectionId")
                        p["collectionName"] = collection_map.get(c_id)

                        all_prompts.append(p)
            except Exception as sube:
                logger.warning(f"Could not fetch prompts from enterprise asset library: {sube}")

        enabled_prompts = []

        for prompt in all_prompts:
            prompt_id = prompt.get("id")
            if not prompt_id:
                continue

            # 1. Filter Check: Skip if explicitly disabled by admin
            prompt_config = prompts_attributes.get(prompt_id, {})
            if prompt_config.get("enabled") is False:
                continue

            # 2. Attribute Injection: Add the Dataiku authorship flag
            prompt["isCreatedByDataiku"] = prompt.get("collectionId") == "DATAIKU"

            enabled_prompts.append(prompt)

        response = {"prompts": enabled_prompts}
        return jsonify({"data": response}), 200
    except Exception as e:
        logger.exception(f"Error fetching prompts library: {e}")
        return jsonify({"error": str(e)}), 500
