"""外部 API 代理转发"""

from __future__ import annotations

import logging
from typing import Any

import httpx

from tool_agent.models import ToolMeta

logger = logging.getLogger(__name__)


class APIProxy:
    """无状态代理，直接转发请求到第三方 API"""

    async def run(self, tool: ToolMeta, params: dict[str, Any], stream: bool = False) -> dict[str, Any]:
        """转发请求到外部 API"""
        endpoint = tool.runtime.entry
        headers = {k: v for k, v in tool.runtime.env.items() if k.startswith("HEADER_")}

        try:
            async with httpx.AsyncClient(timeout=30) as client:
                resp = await client.post(endpoint, json=params, headers=headers)
                return {"status": "success", "result": resp.json()}
        except Exception as e:
            return {"status": "error", "error": str(e)}
