"""Call DAARION router: /v1/agents/{agent_id}/infer and /v1/tools/execute."""
import logging
from typing import Any, Dict, Optional

import httpx

logger = logging.getLogger(__name__)


async def infer(
    base_url: str,
    agent_id: str,
    prompt: str,
    *,
    model: Optional[str] = None,
    system_prompt: Optional[str] = None,
    metadata: Optional[Dict[str, Any]] = None,
    timeout: float = 120.0,
    api_key: str = "",
) -> Dict[str, Any]:
    """POST /v1/agents/{agent_id}/infer. Returns { response, model, backend, ... }."""
    url = f"{base_url.rstrip('/')}/v1/agents/{agent_id}/infer"
    headers = {"Content-Type": "application/json"}
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    body = {
        "prompt": prompt,
        "metadata": metadata or {},
        "max_tokens": 2048,
        "temperature": 0.4,
    }
    if model:
        body["model"] = model
    if system_prompt:
        body["system_prompt"] = system_prompt
    async with httpx.AsyncClient(timeout=timeout) as client:
        r = await client.post(url, json=body, headers=headers)
        r.raise_for_status()
        return r.json()


async def execute_tool(
    base_url: str,
    tool: str,
    action: str,
    params: Optional[Dict[str, Any]] = None,
    *,
    agent_id: str = "sofiia",
    timeout: float = 60.0,
    api_key: str = "",
) -> Dict[str, Any]:
    """POST /v1/tools/execute. Returns { status, data, error }."""
    url = f"{base_url.rstrip('/')}/v1/tools/execute"
    headers = {"Content-Type": "application/json"}
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    body = {
        "tool": tool,
        "action": action,
        "agent_id": agent_id,
        **(params or {}),
    }
    async with httpx.AsyncClient(timeout=timeout) as client:
        r = await client.post(url, json=body, headers=headers)
        r.raise_for_status()
        return r.json()


async def health(base_url: str, timeout: float = 5.0) -> Dict[str, Any]:
    """GET /healthz or /health. Returns { ok, status?, ... }."""
    for path in ("/healthz", "/health", "/"):
        try:
            async with httpx.AsyncClient(timeout=timeout) as client:
                r = await client.get(f"{base_url.rstrip('/')}{path}")
                return {"ok": r.status_code == 200, "status": r.status_code, "path": path}
        except Exception as e:
            logger.debug("health %s%s failed: %s", base_url, path, e)
    return {"ok": False, "error": "unreachable"}
