# src/agentsh_secure_sandbox/toolset/openai_agents.py
"""OpenAI Agents SDK integration — SecureSandboxAgentTools.

Exposes agentsh-secured sandbox tools as OpenAI FunctionTool instances
for use with Agent and Runner.
"""
from __future__ import annotations

import copy
import json
from typing import Any

from typing_extensions import Self

from agents import FunctionTool, RunContextWrapper

from ..core.types import SecuredSandbox, SandboxAdapter, SecureConfig
from ._base import SecureSandboxTools, TOOL_DEFS


class SecureSandboxAgentTools:
    """OpenAI Agents SDK tools providing agentsh-secured sandbox access.

    Not concurrency-safe. Do not share across concurrent agent runs.

    Usage::

        sandbox_tools = SecureSandboxAgentTools(e2b(raw))
        async with sandbox_tools:
            agent = Agent(name="Coder", tools=sandbox_tools.get_tools())
            result = await Runner.run(agent, "Create a server")
    """

    def __init__(
        self,
        adapter: SandboxAdapter,
        config: SecureConfig | None = None,
    ) -> None:
        self._tools = SecureSandboxTools(adapter, config)

    async def __aenter__(self) -> Self:
        await self._tools.__aenter__()
        return self

    async def __aexit__(self, *args: Any) -> None:
        await self._tools.__aexit__(*args)

    @property
    def sandbox(self) -> SecuredSandbox:
        return self._tools.sandbox

    def get_tools(self) -> list[FunctionTool]:
        return [
            self._make_tool("run_command"),
            self._make_tool("write_file"),
            self._make_tool("read_file"),
        ]

    def _make_tool(self, name: str) -> FunctionTool:
        defn = TOOL_DEFS[name]
        tools_ref = self._tools

        async def on_invoke(ctx: RunContextWrapper[Any], args_json: str) -> str:
            args = json.loads(args_json)
            return await tools_ref.call_tool(name, args)

        return FunctionTool(
            name=defn["name"],
            description=defn["description"],
            params_json_schema=copy.deepcopy(defn["parameters"]),
            on_invoke_tool=on_invoke,
        )
