"""Unl in an agent you build with the OpenAI Agents SDK.

Unl is your why agent in your mix of agents. It holds what you have already decided in a project,
each decision with its reason. This file adds Unl to an agent you build: the agent asks Unl before it
acts, and keeps its work within what you decided. Your agent keeps its own model, tools and way of
working; Unl never decides for you and never replaces a tool you already run.

    pip install openai-agents
    export UNL_KEY=...        # a key from https://unlimitless.ai/portal/keys
    export OPENAI_API_KEY=...     # your agent's own model, as you already run it

    python unl_openai_agents.py --check          # is Unl on? no model call
    python unl_openai_agents.py "your request"   # run the agent with Unl
"""
import asyncio
import os
import sys

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

UNL_MCP_URL = "https://api.unlimitless.ai/mcp"

UNL_INSTRUCTIONS = (
    "Unl holds what the person has already decided in this project, each decision with its reason. "
    "Before you change direction, re-decide something, or act on a choice the person may already have "
    "settled, call the unl tool ask_unl with the step you are about to take, in your own words. "
    "If the step goes against one of the decisions that come back, do not take it: say which decision "
    "it crosses and why, and ask the person. If a decision bears on the step, act within it. If nothing "
    "bears, carry on. Unl never decides for the person and never changes what they decided."
)


def unl_server() -> MCPServerStreamableHttp:
    key = os.environ.get("UNL_KEY")
    if not key:
        sys.exit("Set UNL_KEY to a key from https://unlimitless.ai/portal/keys")
    return MCPServerStreamableHttp(
        name="unl",
        params={"url": UNL_MCP_URL, "headers": {"Authorization": f"Bearer {key}"}, "timeout": 30},
        client_session_timeout_seconds=60,
    )


async def check() -> None:
    """Connect, list Unl's tools and ask one question. No model call."""
    async with unl_server() as unl:
        tools = [t.name for t in await unl.list_tools()]
        print("Unl is on. Tools:", ", ".join(sorted(tools)))
        answer = await unl.call_tool("ask_unl", {"query": "What have I already decided in this project?"})
        text = "".join(getattr(c, "text", "") for c in answer.content)
        print(f"ask_unl answered ({len(text)} characters).")


async def run(request: str) -> None:
    async with unl_server() as unl:
        agent = Agent(
            name="your-agent",
            instructions="You help the person with their project. " + UNL_INSTRUCTIONS,
            mcp_servers=[unl],
        )
        result = await Runner.run(agent, request)
        print(result.final_output)


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--check":
        asyncio.run(check())
    elif len(sys.argv) > 1:
        asyncio.run(run(" ".join(sys.argv[1:])))
    else:
        sys.exit(__doc__)
