"""A PydanticAI agent trading tradefloor over MCP.

    pip install "pydantic-ai-slim[mcp,anthropic]"
    python -m tradefloor_serve                              # a local server, in another terminal
    ANTHROPIC_API_KEY=... python examples/agents/pydantic_ai_mcp.py
    python examples/agents/pydantic_ai_mcp.py --offline      # a scripted model, no key needed

For the hosted service, set TF_URL=https://app.tradefloor.dev and
TF_KEY=tfk_... Any model PydanticAI supports works; set
TF_MODEL (default anthropic:claude-sonnet-4-5).

include_instructions=True passes the server's instructions (the loop, how
time and fills work, idempotency keys) to the model.
"""

from __future__ import annotations

import argparse
import asyncio
import os

from pydantic_ai import Agent
from pydantic_ai.mcp import MCPToolset

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 None
    tradefloor = MCPToolset(URL, headers=headers, include_instructions=True)
    if offline:
        from _offline import pydantic_ai_model
        model = pydantic_ai_model()
    else:
        model = os.environ.get("TF_MODEL", "anthropic:claude-sonnet-4-5")
    agent = Agent(model, toolsets=[tradefloor],
                  instructions="You trade in a simulated market through the tradefloor tools.")
    async with agent:
        result = await agent.run(TASK)
    print(result.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 a real one")
    asyncio.run(main(parser.parse_args().offline))
