from __future__ import annotations
import os, json
from typing import List
from .openapi_loader import load_openapi_operations
from .registry import ToolRegistry, ToolSpec

def discover_openapi_tools(directory: str, registry: ToolRegistry) -> List[str]:
    added: List[str] = []
    for root, _, files in os.walk(directory):
        for f in files:
            if not f.lower().endswith(".json"):
                continue
            path = os.path.join(root, f)
            with open(path, "r", encoding="utf-8") as fp:
                spec = json.load(fp)
            for op in load_openapi_operations(spec):
                registry.register(
                    ToolSpec(
                        name=op.tool_name,
                        description=op.description,
                        input_schema=op.input_schema,
                        output_schema=op.output_schema,
                        tags=["openapi", op.method.lower()],
                    ),
                    fn=_unbound_tool(op.tool_name),
                )
                added.append(op.tool_name)
    return added

def _unbound_tool(name: str):
    async def _fn(**kwargs):
        raise RuntimeError(
            f"Tool '{name}' discovered from OpenAPI but not bound to an executor. "
            f"Bind via your HTTP client adapter."
        )
    return _fn
