from __future__ import annotations
import inspect
from typing import Any, Callable

from .registry import get_registry
from .exports import ToolExport, AgentExport, FlowExport, HttpHandlerExport

def _meta(fn: Callable[..., Any]) -> tuple[str, str, bool]:
    return fn.__module__, fn.__qualname__, inspect.iscoroutinefunction(fn)

def tool(name: str):
    def decorator(fn: Callable[..., Any]):
        reg = get_registry()
        module, qualname, is_async = _meta(fn)
        reg.tools[name] = ToolExport(name=name, fn=fn, module=module, qualname=qualname, is_async=is_async)
        return fn
    return decorator

def agent(name: str):
    def decorator(fn: Callable[..., Any]):
        reg = get_registry()
        module, qualname, is_async = _meta(fn)
        reg.agents[name] = AgentExport(name=name, fn=fn, module=module, qualname=qualname, is_async=is_async)
        return fn
    return decorator

def flow(name: str):
    def decorator(fn: Callable[..., Any]):
        reg = get_registry()
        module, qualname, _ = _meta(fn)
        reg.flows[name] = FlowExport(name=name, fn=fn, graph_builder=None, module=module, qualname=qualname)
        return fn
    return decorator

def flow_graph(name: str, builder: Callable[..., Any]):
    reg = get_registry()
    module, qualname, _ = _meta(builder)
    reg.flows[name] = FlowExport(name=name, fn=None, graph_builder=builder, module=module, qualname=qualname)
    return builder

def http_get(path: str):
    def decorator(fn: Callable[..., Any]):
        reg = get_registry()
        module, qualname, is_async = _meta(fn)
        reg.http_handlers.append(HttpHandlerExport("GET", path, fn, module, qualname, is_async))
        return fn
    return decorator

def http_post(path: str):
    def decorator(fn: Callable[..., Any]):
        reg = get_registry()
        module, qualname, is_async = _meta(fn)
        reg.http_handlers.append(HttpHandlerExport("POST", path, fn, module, qualname, is_async))
        return fn
    return decorator
