"""
Tool-plugin CLI commands for AI Lab
"""
import json

from pygeai import logger
from pygeai.cli.commands import Option
from pygeai.cli.commands.common import get_boolean_value
from pygeai.cli.commands.lab.common import get_tool_parameters
from pygeai.cli.commands.lab.options import PROJECT_ID_OPTION
from pygeai.core.common.exceptions import MissingRequirementException
from pygeai.core.utils.console import Console
from pygeai.lab.managers import AILabManager


def list_tool_plugins(option_list: list):
    project_id = None
    count = "100"
    access_scope = "private"
    allow_drafts = True

    for option_flag, option_arg in option_list:
        if option_flag.name == "project_id":
            project_id = option_arg
        if option_flag.name == "count":
            count = option_arg
        if option_flag.name == "access_scope":
            access_scope = option_arg
        if option_flag.name == "allow_drafts":
            allow_drafts = get_boolean_value(option_arg)

    try:
        manager = AILabManager(project_id=project_id)
        from pygeai.lab.models import FilterSettings
        filter_settings = FilterSettings(
            count=count,
            access_scope=access_scope,
            allow_drafts=allow_drafts
        )
        result = manager.list_tool_plugins(filter_settings=filter_settings)
        Console.write_stdout(f"Tool-plugin list: \n{result}")
    except Exception as e:
        Console.write_stderr(f"Error listing tool-plugins (feature may not be available): {e}")


list_tool_plugins_options = [
    PROJECT_ID_OPTION,
    Option(
        "count",
        ["--count"],
        "Number of tool-plugins to retrieve. Defaults to '100'.",
        True
    ),
    Option(
        "access_scope",
        ["--access-scope"],
        'Access scope of the tool-plugins, either "public" or "private". Defaults to "private".',
        True
    ),
    Option(
        "allow_drafts",
        ["--allow-drafts"],
        "Whether to include draft tool-plugins. Defaults to 1 (True).",
        True
    )
]


def get_tool_plugin(option_list: list):
    project_id = None
    plugin_id_or_name = None
    revision = "0"
    version = "0"
    allow_drafts = True

    for option_flag, option_arg in option_list:
        if option_flag.name == "project_id":
            project_id = option_arg
        if option_flag.name == "plugin_id_or_name":
            plugin_id_or_name = option_arg
        if option_flag.name == "revision":
            revision = option_arg
        if option_flag.name == "version":
            version = option_arg
        if option_flag.name == "allow_drafts":
            allow_drafts = get_boolean_value(option_arg)

    if not plugin_id_or_name:
        raise MissingRequirementException("Tool-plugin ID or name must be specified.")

    try:
        manager = AILabManager(project_id=project_id)
        from pygeai.lab.models import FilterSettings
        filter_settings = FilterSettings(
            revision=revision,
            version=version,
            allow_drafts=allow_drafts
        )
        result = manager.get_tool_plugin(
            plugin_id_or_name=plugin_id_or_name,
            filter_settings=filter_settings
        )
        Console.write_stdout(f"Tool-plugin detail: \n{result}")
    except Exception as e:
        Console.write_stderr(f"Error getting tool-plugin (feature may not be available): {e}")


get_tool_plugin_options = [
    PROJECT_ID_OPTION,
    Option(
        "plugin_id_or_name",
        ["--plugin-id-or-name", "--pid"],
        "Unique identifier or name of the tool-plugin to retrieve",
        True
    ),
    Option(
        "revision",
        ["--revision", "-r"],
        'Revision of the tool-plugin to retrieve. Defaults to "0" (latest).',
        True
    ),
    Option(
        "version",
        ["--version", "-v"],
        'Version of the tool-plugin to retrieve. Defaults to "0" (latest).',
        True
    ),
    Option(
        "allow_drafts",
        ["--allow-drafts"],
        "Whether to allow draft tool-plugins. Defaults to 1 (True).",
        True
    )
]


def get_tool_plugin_config(option_list: list):
    project_id = None
    plugin_id_or_name = None
    revision = "0"
    version = "0"
    allow_drafts = True

    for option_flag, option_arg in option_list:
        if option_flag.name == "project_id":
            project_id = option_arg
        if option_flag.name == "plugin_id_or_name":
            plugin_id_or_name = option_arg
        if option_flag.name == "revision":
            revision = option_arg
        if option_flag.name == "version":
            version = option_arg
        if option_flag.name == "allow_drafts":
            allow_drafts = get_boolean_value(option_arg)

    if not plugin_id_or_name:
        raise MissingRequirementException("Tool-plugin ID or name must be specified.")

    try:
        manager = AILabManager(project_id=project_id)
        from pygeai.lab.models import FilterSettings
        filter_settings = FilterSettings(
            revision=revision,
            version=version,
            allow_drafts=allow_drafts
        )
        result = manager.get_tool_plugin_config(
            plugin_id_or_name=plugin_id_or_name,
            filter_settings=filter_settings
        )
        Console.write_stdout(f"Tool-plugin configuration: \n{result}")
    except Exception as e:
        Console.write_stderr(f"Error getting tool-plugin config (feature may not be available): {e}")


get_tool_plugin_config_options = [
    PROJECT_ID_OPTION,
    Option(
        "plugin_id_or_name",
        ["--plugin-id-or-name", "--pid"],
        "Unique identifier or name of the tool-plugin",
        True
    ),
    Option(
        "revision",
        ["--revision", "-r"],
        'Revision of the tool-plugin. Defaults to "0" (latest).',
        True
    ),
    Option(
        "version",
        ["--version", "-v"],
        'Version of the tool-plugin. Defaults to "0" (latest).',
        True
    ),
    Option(
        "allow_drafts",
        ["--allow-drafts"],
        "Whether to allow draft tool-plugins. Defaults to 1 (True).",
        True
    )
]


def set_tool_plugin_config(option_list: list):
    project_id = None
    plugin_id_or_name = None
    parameters = []

    for option_flag, option_arg in option_list:
        if option_flag.name == "project_id":
            project_id = option_arg
        if option_flag.name == "plugin_id_or_name":
            plugin_id_or_name = option_arg
        if option_flag.name == "parameter":
            parameters.append(option_arg)

    if not plugin_id_or_name:
        raise MissingRequirementException("Tool-plugin ID or name must be specified.")
    if not parameters:
        raise MissingRequirementException("At least one parameter must be specified.")

    tool_parameters = get_tool_parameters(parameters)

    try:
        manager = AILabManager(project_id=project_id)
        result = manager.set_tool_plugin_config(
            plugin_id_or_name=plugin_id_or_name,
            parameters=tool_parameters
        )
        Console.write_stdout(f"Set tool-plugin config result: \n{result}")
    except Exception as e:
        Console.write_stderr(f"Error setting tool-plugin config (feature may not be available): {e}")


set_tool_plugin_config_options = [
    PROJECT_ID_OPTION,
    Option(
        "plugin_id_or_name",
        ["--plugin-id-or-name", "--pid"],
        "Unique identifier or name of the tool-plugin",
        True
    ),
    Option(
        "parameter",
        ["--parameter", "-p"],
        "Parameter in JSON format, e.g., '{\"key\": \"api_key\", \"value\": \"sk-...\" }'. Multiple parameters can be specified by using this flag multiple times.",
        True
    )
]
