"""Unl in an agent you build with the Microsoft Agent Framework (the successor to AutoGen).

Unl is your why agent in your mix of agents: the infra agent for your fleet, the one that carries your
why to every other agent. 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 orchestration; Unl never decides for
you and never replaces a tool you already run.

    pip install agent-framework
    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
    export OPENAI_MODEL=...      # which model, e.g. the one your agent already uses

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

from agent_framework import Agent, MCPStreamableHTTPTool

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_tool() -> MCPStreamableHTTPTool:
    key = os.environ.get("UNL_KEY")
    if not key:
        sys.exit("Set UNL_KEY to a key from https://unlimitless.ai/portal/keys")
    return MCPStreamableHTTPTool(
        name="unl",
        url=UNL_MCP_URL,
        static_headers={"Authorization": f"Bearer {key}"},
        request_timeout=60,
        load_prompts=False,
    )


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


async def run(request: str) -> None:
    from agent_framework.openai import OpenAIChatClient

    async with unl_tool() as unl:
        agent = Agent(
            client=OpenAIChatClient(),  # reads OPENAI_API_KEY and OPENAI_MODEL
            name="your-agent",
            instructions="You help the person with their project. " + UNL_INSTRUCTIONS,
            tools=[unl],
        )
        print(await agent.run(request))


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__)
