"""LangChain adapter over the shared TrueFetch REST tools."""

import sys
from pathlib import Path
from langchain_core.tools import StructuredTool, ToolException

try:
    import truefetch_rest as core
except ModuleNotFoundError as error:
    if error.name != "truefetch_rest":
        raise
    sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "python"))
    import truefetch_rest as core

API = core.API
JobInput = core.JobInput


def make_tools(api_key, **options):
    def adapt(rest):
        def invoke(**arguments):
            try:
                return rest.invoke(arguments)
            except core.ToolException as error:
                raise ToolException(str(error)) from None

        return StructuredTool.from_function(
            invoke, name=rest.name, description=rest.description, args_schema=rest.args_schema
        )

    return [adapt(rest) for rest in core.make_tools(api_key, api_url=API, **options)]


def recover_results(tools, task_id, **options):
    try:
        return core.recover_results(tools, task_id, **options)
    except core.ToolException as error:
        raise ToolException(str(error)) from None
