from langchain_core.runnables import RunnableConfig

from universal_mcp.agentr.agent_builder_registry import AgentBuilderRegistry
from universal_mcp.agentr.client import AgentrClient
from universal_mcp.agentr.registry import AgentrRegistry
from universal_mcp.agents.codeact0 import CodeActPlaybookAgent
from universal_mcp.agents.codeact0.config import ContextSchema


async def agent(config: RunnableConfig):
    cfg = ContextSchema(**config.get("configurable", {}))
    client = AgentrClient(auth_token=cfg.auth_token, timezone=cfg.timezone)
    registry = AgentrRegistry(client)

    if cfg.agent_id:
        agent_builder_registry = AgentBuilderRegistry(client=client, default_agent_id=cfg.agent_id)
    elif cfg.template_id:
        agent_builder_registry = AgentBuilderRegistry(client=client, default_template_id=cfg.template_id)
    else:
        agent_builder_registry = AgentBuilderRegistry(client=client)

    agent_obj = CodeActPlaybookAgent(
        name="CodeAct Agent",
        instructions=cfg.instructions,
        # model="anthropic:claude-sonnet-4-5-20250929",
        model=cfg.model,
        registry=registry,
        agent_builder_registry=agent_builder_registry,
    )
    return await agent_obj._build_graph()
