"""An OpenAI Agents SDK agent trading tradefloor over MCP.

    pip install openai-agents
    python -m tradefloor_serve                              # a local server, in another terminal
    OPENAI_API_KEY=... python examples/agents/openai_agents_mcp.py
    python examples/agents/openai_agents_mcp.py --offline    # a scripted model, no key needed

For the hosted service, set TF_URL=https://app.tradefloor.dev and
TF_KEY=tfk_...

The SDK does not hand the MCP server's instructions to the model, so this
example reads them after connecting and puts them in the agent's
instructions. Its retries (max_retry_attempts) are safe because every write
the agent makes carries an idempotency_key.
"""

from __future__ import annotations

import argparse
import asyncio
import os

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

URL = os.environ.get("TF_URL", "http://127.0.0.1:8765").rstrip("/") + "/mcp"
KEY = os.environ.get("TF_KEY")
TASK = ("Open a tradefloor session with 5 names. Look at it, buy 10 shares of one stock, "
        "advance to the close, then close the session. Report the net worth and the caveats.")


async def main(offline: bool) -> None:
    headers = {"Authorization": f"Bearer {KEY}"} if KEY else {}
    async with MCPServerStreamableHttp(params={"url": URL, "headers": headers, "timeout": 30},
                                       name="tradefloor", cache_tools_list=True,
                                       max_retry_attempts=2) as server:
        init = getattr(server, "server_initialize_result", None)
        instructions = getattr(init, "instructions", None) or ""
        if offline:
            from _offline import openai_agents_model
            model = openai_agents_model()
        else:
            model = os.environ.get("OPENAI_MODEL", "gpt-5")
        agent = Agent(name="trader", model=model, mcp_servers=[server],
                      instructions="You trade in a simulated market through the tradefloor tools.\n\n"
                                   + instructions)
        result = await Runner.run(agent, TASK, max_turns=30)
        print(result.final_output)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--offline", action="store_true", help="use a scripted model instead of OpenAI")
    asyncio.run(main(parser.parse_args().offline))
