import pytest
import httpx

from adi_agentic_agi.tools.openapi_binder import bind_openapi_directory
from adi_agentic_agi.tools.http_executor import OpenAPIHttpExecutor, HttpAuth
from adi_agentic_agi.tools.registry import ToolRegistry

@pytest.mark.asyncio
async def test_openapi_binder_executes(tmp_path):
    # create minimal OpenAPI spec
    spec = {
        "openapi": "3.0.0",
        "info": {"title": "T", "version": "1.0"},
        "paths": {
            "/echo": {
                "post": {
                    "operationId": "echo",
                    "requestBody": {
                        "content": {"application/json": {"schema": {"type": "object"}}}
                    },
                    "responses": {
                        "200": {
                            "description": "ok",
                            "content": {"application/json": {"schema": {"type": "object"}}},
                        }
                    },
                }
            }
        },
    }
    d = tmp_path / "specs"
    d.mkdir()
    (d / "api.json").write_text(__import__("json").dumps(spec), encoding="utf-8")

    # mock httpx by monkeypatching executor client transport
    def handler(request: httpx.Request) -> httpx.Response:
        assert request.url.path == "/echo"
        return httpx.Response(200, json={"ok": True})

    transport = httpx.MockTransport(handler)
    ex = OpenAPIHttpExecutor(base_url="https://example.com", auth=HttpAuth())
    # swap internal client
    ex._client = httpx.AsyncClient(transport=transport, base_url="https://example.com")  # type: ignore[attr-defined]

    reg = ToolRegistry()
    bind_openapi_directory(str(d), reg, ex)
    tool = reg.get("echo")
    assert tool is not None
    out = await tool.fn(a=1)
    assert out["ok"] is True
    await ex.aclose()
