from unittest import TestCase
import unittest
from pygeai.lab.managers import AILabManager
from pygeai.lab.plugins.tools.models import ToolPlugin
from pygeai.lab.models import FilterSettings
from pygeai.core.common.exceptions import APIResponseError
import copy


class TestAILabGetToolPluginIntegration(TestCase):

    def setUp(self):
        self.ai_lab_manager = AILabManager()
        self.plugin_id = "test-plugin-id"
        self.filter_settings = FilterSettings(
            revision="0",
            version="0"
        )

    def __get_tool_plugin(self, plugin_id=None, filter_settings: FilterSettings = None):
        return self.ai_lab_manager.get_tool_plugin(
            plugin_id_or_name=self.plugin_id if plugin_id is None else plugin_id,
            filter_settings=self.filter_settings if filter_settings is None else filter_settings
        )

    def test_get_tool_plugin(self):
        plugin = self.__get_tool_plugin()
        self.assertIsInstance(plugin, ToolPlugin, "Expected a tool-plugin")

    @unittest.skip("Skipped: Validate that when no plugin_id is provided, error is raised")
    def test_get_tool_plugin_no_plugin_id(self):
        with self.assertRaises(Exception) as context:
            self.__get_tool_plugin(plugin_id="")

    def test_get_tool_plugin_invalid_plugin_id(self):
        invalid_id = "invalid-plugin-id-12345"
        with self.assertRaises(APIResponseError) as context:
            self.__get_tool_plugin(plugin_id=invalid_id)
        self.assertIn(
            f"Tool plugin not found",
            str(context.exception),
            "Expected an error for invalid tool-plugin id"
        )

    def test_get_tool_plugin_no_revision(self):
        filter_settings = copy.deepcopy(self.filter_settings)
        filter_settings.revision = None
        plugin = self.__get_tool_plugin(filter_settings=filter_settings)

        self.assertIsInstance(plugin, ToolPlugin, "Expected a tool-plugin")
        self.assertGreaterEqual(plugin.revision, 1, "Expected tool-plugin revision to be the latest")

    def test_get_tool_plugin_by_revision(self):
        filter_settings = copy.deepcopy(self.filter_settings)
        filter_settings.revision = "1"
        plugin = self.__get_tool_plugin(filter_settings=filter_settings)

        self.assertEqual(1, plugin.revision, "Expected tool-plugin revision to be 1")

    def test_get_tool_plugin_no_version(self):
        filter_settings = copy.deepcopy(self.filter_settings)
        filter_settings.version = None
        plugin = self.__get_tool_plugin(filter_settings=filter_settings)

        self.assertIsInstance(plugin, ToolPlugin, "Expected a tool-plugin")

    def test_get_tool_plugin_by_version(self):
        filter_settings = copy.deepcopy(self.filter_settings)
        filter_settings.version = "1"
        plugin = self.__get_tool_plugin(filter_settings=filter_settings)

        self.assertIsInstance(plugin, ToolPlugin, "Expected a tool-plugin")
