"""Unl in a crew you build with CrewAI.

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 gives every agent in your crew Unl's tools: an agent asks Unl before it acts, and
keeps its work within what you decided. Your crew keeps its own process, models and tools; Unl never
decides for you and never replaces a tool you already run.

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

    python unl_crewai.py --check          # is Unl on? no model call
    python unl_crewai.py "your request"   # run a two-agent crew with Unl
"""
import os
import sys

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_headers() -> dict:
    key = os.environ.get("UNL_KEY")
    if not key:
        sys.exit("Set UNL_KEY to a key from https://unlimitless.ai/portal/keys")
    return {"Authorization": f"Bearer {key}"}


def check() -> None:
    """Connect the way your crew will, list Unl's tools and ask one question. No model call."""
    from crewai import Agent
    from crewai.mcp import MCPServerHTTP

    agent = Agent(role="check", goal="check", backstory="check", mcps=[MCPServerHTTP(url=UNL_MCP_URL, headers=unl_headers())])
    tools = agent.get_mcp_tools(agent.mcps)
    print("Unl is on. Tools:", ", ".join(sorted(t.name for t in tools)))
    ask = next(t for t in tools if t.name.endswith("ask_unl"))
    text = str(ask.run(query="What have I already decided in this project?"))
    print(f"ask_unl answered ({len(text)} characters).")


def run(request: str) -> None:
    from crewai import Agent, Crew, Task
    from crewai.mcp import MCPServerHTTP

    unl = MCPServerHTTP(url=UNL_MCP_URL, headers=unl_headers())
    planner = Agent(
        role="Planner",
        goal="Plan the work so it stays within what the person has already decided.",
        backstory="You plan changes to the person's project. " + UNL_INSTRUCTIONS,
        mcps=[unl],
    )
    builder = Agent(
        role="Builder",
        goal="Carry out the plan within what the person has already decided.",
        backstory="You make the changes the plan calls for. " + UNL_INSTRUCTIONS,
        mcps=[unl],
    )
    plan = Task(description=request, expected_output="A short plan, naming any decision it rests on.", agent=planner)
    build = Task(description="Carry out the plan.", expected_output="What you did, and the decisions you kept to.", agent=builder)
    print(Crew(agents=[planner, builder], tasks=[plan, build]).kickoff())


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