"""Native CrewAI tools sharing the TrueFetch REST contract and recovery."""

import asyncio
import sys
from pathlib import Path
from pydantic import PrivateAttr
from crewai.tools import BaseTool

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
TrueFetchError = core.ToolException


def never_cache(_arguments=None, _result=None):
    return False


class TrueFetchTool(BaseTool):
    _rest: object = PrivateAttr()

    def __init__(self, rest):
        super().__init__(
            name=rest.name,
            description=rest.description,
            args_schema=rest.args_schema,
            cache_function=never_cache,
        )
        self._rest = rest

    def _run(self, **arguments) -> dict:
        return self._rest.invoke(arguments)

    async def _arun(self, **arguments) -> dict:
        return await asyncio.to_thread(self._run, **arguments)


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


def recover_results(tools, task_id, **options):
    class Reader:
        def __init__(self, tool):
            self.name, self.tool = tool.name, tool

        def invoke(self, arguments):
            return self.tool.run(**arguments)

    return core.recover_results([Reader(tool) for tool in tools], task_id, **options)
