"""
Shared parameter helpers for Agent Hub plugin components.

This module provides dynamic parameter choices for both recipes and connectors
that need to access Agent Hub webapp data.
"""

import os

import dataiku

TARGET_APP_AGENT_HUB = "agenthub"
TARGET_APP_ANSWERS = "answers"
_WEBAPP_TYPE_PREFIX = "webapp_agent-hub"
_WEBAPP_TYPE_LIGHT_SUFFIX = "light"
_ANSWERS_EXCLUDED_EXPORT_TABLES = {"agent_shares", "agents", "draft_conversations"}


def do(payload, config, plugin_config, inputs):
    """Main entry point for parameter choice resolution."""
    return do_for_target_app(payload, config, TARGET_APP_AGENT_HUB)


def do_for_target_app(payload, config, target_app):
    """Shared parameter provider for export recipes."""
    param_name = payload.get("parameterName")

    if param_name == "project_key":
        return get_project_choices()
    elif param_name == "webapp_id":
        return get_webapp_choices(config, target_app=target_app)
    elif param_name == "table_name":
        return get_table_choices(config, target_app=target_app)

    return {"choices": []}


def get_project_choices():
    """Get list of available DSS projects."""
    try:
        client = dataiku.api_client()
        projects = client.list_projects()

        choices = [
            {"value": p["projectKey"], "label": f"{p.get('name', p['projectKey'])} ({p['projectKey']})"}
            for p in projects
        ]

        current_project = os.environ.get("DKU_CURRENT_PROJECT_KEY")
        if current_project:
            choices = sorted(choices, key=lambda x: (x["value"] != current_project, x["label"]))

        return {"choices": choices}
    except Exception as e:
        print(f"Error listing projects: {e}")
        return {"choices": []}


def _is_matching_webapp_type(webapp_type, target_app):
    if not webapp_type.startswith(_WEBAPP_TYPE_PREFIX):
        return False

    is_light = webapp_type.endswith(_WEBAPP_TYPE_LIGHT_SUFFIX)
    if target_app == TARGET_APP_ANSWERS:
        return is_light
    return not is_light


def get_webapp_choices(config, target_app=TARGET_APP_AGENT_HUB):
    """Get list of webapps in the selected project."""
    project_key = config.get("project_key")

    if not project_key:
        return {"choices": [], "message": "Please select a project first"}

    try:
        client = dataiku.api_client()
        project = client.get_project(project_key)
        webapps = project.list_webapps()

        matching_webapps = [w for w in webapps if _is_matching_webapp_type(w.get("type", ""), target_app)]

        choices = [{"value": w["id"], "label": f"{w.get('name', w['id'])} ({w['id']})"} for w in matching_webapps]

        return {"choices": choices}
    except Exception as e:
        print(f"Error listing webapps: {e}")
        return {"choices": [], "message": f"Error loading webapps: {str(e)}"}


def get_table_choices(config, target_app=TARGET_APP_AGENT_HUB):
    """Get list of exportable tables from the selected webapp's database."""
    project_key = config.get("project_key")
    webapp_id = config.get("webapp_id")

    if not project_key:
        return {"choices": [], "message": "Select a project first"}

    if not webapp_id:
        return {"choices": [], "message": "Select a webapp first"}

    try:
        dip_home = os.environ.get("DIP_HOME")
        if not dip_home:
            return {"choices": [], "message": "DIP_HOME not found"}

        # workload_folder = os.path.join(dip_home, "workload-folders", "webapps", project_key, webapp_id)

        # db_path = os.path.join(workload_folder, "data_store.db")

        # if not os.path.exists(db_path):
        #     return {"choices": [], "message": "Database not found. Ensure the webapp has been started."}

        from backend.services.export_service import ExportService

        tables = ExportService().list_exportable_tables()
        if target_app == TARGET_APP_ANSWERS:
            tables = [table for table in tables if table not in _ANSWERS_EXCLUDED_EXPORT_TABLES]

        table_descriptions = {
            "agents": "Agent configurations and metadata",
            "conversations": "Conversation metadata",
            "messages": "Messages with artifacts and events",
            "message_agents": "Message-agent relationships",
            "preferences": "User preferences",
            "draft_conversations": "Draft conversation data",
            "agent_shares": "Agent sharing permissions",
            "message_attachments": "Attachment metadata",
            "derived_documents": "Derived document metadata",
        }

        choices = [
            {"value": table, "label": f"{table} - {table_descriptions.get(table, 'Data table')}"} for table in tables
        ]

        return {"choices": choices}

    except Exception as e:
        print(f"Error loading tables: {e}")
        return {"choices": [], "message": f"Error loading tables: {str(e)}"}
