"""Raeto for agent frameworks: LangChain / LangGraph and the OpenAI Agents SDK. One file; needs httpx (which the
openai package already installs).

Every framework here takes an OpenAI-compatible base URL and an httpx client. The clients made here add Raeto's
headers to each call: the agent's name (X-Raeto-Agent) and the task it belongs to (X-Raeto-Task, -Type, -Budget), so
cost per task, task budgets, loop breaking and cache-aware routing work without touching your agent code.

    from raeto_frameworks import task, agent, raeto_chat_model, use_raeto_agents_sdk, raeto_model

    # LangChain / LangGraph
    llm = raeto_chat_model(api_key=os.environ["RAETO_KEY"], agent="researcher")   # ChatOpenAI on raeto/auto
    with task(type="research", budget_usd=0.10):
        graph.invoke(inputs)

    # OpenAI Agents SDK
    use_raeto_agents_sdk(api_key=os.environ["RAETO_KEY"])
    triage_agent = Agent(name="Triage", instructions="...", model=raeto_model())   # raeto/auto
    with task(type="triage"):
        result = await Runner.run(triage_agent, "My order never came")

Every call made inside `with task(...)` is one Raeto task. Raeto closes a task after 30 idle minutes; call end_task()
just before a task's last call to close it there. `with agent("planner"):` names the agent for calls made inside it
(one LangGraph node, a sub-agent). Contexts follow asyncio tasks and LangChain's thread pools (contextvars).
"""
from __future__ import annotations

import contextlib
import contextvars
import secrets
import time

import httpx

RAETO_BASE_URL = "https://api.raeto.cc/v1"

_task: contextvars.ContextVar = contextvars.ContextVar("raeto_task", default=None)
_agent: contextvars.ContextVar = contextvars.ContextVar("raeto_agent", default=None)
_agents_client = None


def _new_id() -> str:
    return "t_" + format(int(time.time() * 1000), "x") + secrets.token_hex(3)


@contextlib.contextmanager
def task(id: str | None = None, type: str | None = None, budget_usd: float | None = None, model: str | None = None):
    """Run the block as one Raeto task. model: "sticky", "free" or "auto". Yields the task id."""
    t = {"id": str(id or _new_id()), "type": type, "budget_usd": budget_usd, "model": model, "end": None}
    tok = _task.set(t)
    try:
        yield t["id"]
    finally:
        _task.reset(tok)


@contextlib.contextmanager
def agent(name: str):
    """Name the agent for every call made inside the block."""
    tok = _agent.set(str(name))
    try:
        yield
    finally:
        _agent.reset(tok)


def end_task(status: str = "done") -> None:
    """Mark the current task's next call as its last (done or failed)."""
    t = _task.get()
    if t:
        t["end"] = "failed" if status == "failed" else "done"


def current_task() -> str | None:
    t = _task.get()
    return t["id"] if t else None


def raeto_headers(default_agent: str | None = None) -> dict:
    """Raeto's headers for the current context."""
    h = {}
    a = _agent.get() or default_agent
    if a:
        h["x-raeto-agent"] = str(a)
    t = _task.get()
    if t:
        h["x-raeto-task"] = t["id"]
        if t.get("type"):
            h["x-raeto-task-type"] = str(t["type"])
        if t.get("budget_usd") is not None:
            h["x-raeto-task-budget"] = str(t["budget_usd"])
        if t.get("model"):
            h["x-raeto-task-model"] = str(t["model"])
        if t.get("end"):
            h["x-raeto-task-end"] = t["end"]
            t["end"] = None
    return h


def raeto_http_client(agent: str | None = None, **kw) -> httpx.Client:
    """An httpx.Client that adds Raeto's headers to every request."""
    def hook(request: httpx.Request) -> None:
        for k, v in raeto_headers(agent).items():
            request.headers[k] = v
    hooks = kw.pop("event_hooks", {}) or {}
    return httpx.Client(event_hooks={**hooks, "request": [hook, *hooks.get("request", [])]}, timeout=kw.pop("timeout", 600), **kw)


def raeto_async_http_client(agent: str | None = None, **kw) -> httpx.AsyncClient:
    """An httpx.AsyncClient that adds Raeto's headers to every request."""
    async def hook(request: httpx.Request) -> None:
        for k, v in raeto_headers(agent).items():
            request.headers[k] = v
    hooks = kw.pop("event_hooks", {}) or {}
    return httpx.AsyncClient(event_hooks={**hooks, "request": [hook, *hooks.get("request", [])]}, timeout=kw.pop("timeout", 600), **kw)


def raeto_openai(api_key: str, agent: str | None = None, base_url: str = RAETO_BASE_URL, **kw):
    """openai.OpenAI on Raeto."""
    from openai import OpenAI
    return OpenAI(api_key=api_key, base_url=base_url, http_client=raeto_http_client(agent), **kw)


def raeto_async_openai(api_key: str, agent: str | None = None, base_url: str = RAETO_BASE_URL, **kw):
    """openai.AsyncOpenAI on Raeto."""
    from openai import AsyncOpenAI
    return AsyncOpenAI(api_key=api_key, base_url=base_url, http_client=raeto_async_http_client(agent), **kw)


def raeto_chat_model(api_key: str, agent: str | None = None, model: str = "raeto/auto", base_url: str = RAETO_BASE_URL, **kw):
    """LangChain / LangGraph: a ChatOpenAI (langchain-openai) on Raeto, sync and async."""
    from langchain_openai import ChatOpenAI
    return ChatOpenAI(model=model, api_key=api_key, base_url=base_url,
                      http_client=raeto_http_client(agent), http_async_client=raeto_async_http_client(agent), **kw)


def use_raeto_agents_sdk(api_key: str, agent: str | None = None, base_url: str = RAETO_BASE_URL, tracing: bool = False):
    """OpenAI Agents SDK: make Raeto the default client, on chat completions. Tracing to OpenAI is turned off unless
    tracing=True (it needs an OpenAI key). Returns the client."""
    global _agents_client
    import agents as sdk
    client = _agents_client = raeto_async_openai(api_key, agent, base_url)
    sdk.set_default_openai_client(client, use_for_tracing=False)
    sdk.set_default_openai_api("chat_completions")
    if not tracing:
        sdk.set_tracing_disabled(True)
    return client


def raeto_model(model: str = "raeto/auto"):
    """OpenAI Agents SDK: the model to give an Agent (the SDK reads "raeto/..." as a provider prefix, so pass this
    instead of the string). Call use_raeto_agents_sdk first."""
    from agents import OpenAIChatCompletionsModel
    if _agents_client is None:
        raise RuntimeError("Call use_raeto_agents_sdk(api_key=...) first.")
    return OpenAIChatCompletionsModel(model=model, openai_client=_agents_client)
