"""
StashGamma MCP endpoint — programmatic Python client using the official `mcp` SDK's
Streamable HTTP client. Use this when you're building your own agent/script and want
to call the `get_eod_data` tool directly, without a chat UI (Claude Desktop/Code) in
the loop.

    pip install -r requirements.txt
    export STASHGAMMA_API_KEY=sg_live_...
    python python_client.py QQQ 2026-07-01 2026-08-01

Same auth, same rate-limit bucket as the REST API — see ../python/eod_quickstart.py
for the plain-REST equivalent, and https://www.stashgamma.com/developer-docs#mcp for
the full protocol reference.
"""
import asyncio
import json
import os
import sys

from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

MCP_URL = "https://www.stashgamma.com/api/dataapi/mcp"


async def get_eod_data(symbol: str, date_from: str | None, date_to: str | None, api_key: str) -> dict:
    async with streamablehttp_client(MCP_URL, headers={"X-Api-Key": api_key}) as (
        read_stream,
        write_stream,
        _get_session_id,
    ):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()

            args = {"symbol": symbol}
            if date_from:
                args["from"] = date_from
            if date_to:
                args["to"] = date_to

            result = await session.call_tool("get_eod_data", args)

            if result.isError:
                # Rate-limited, bad symbol, no data, etc. — the reason is in the text content,
                # not an exception, so your agent/script can decide how to react.
                raise RuntimeError(result.content[0].text)

            return json.loads(result.content[0].text)


async def main():
    symbol = sys.argv[1] if len(sys.argv) > 1 else "QQQ"
    date_from = sys.argv[2] if len(sys.argv) > 2 else "2026-07-01"
    date_to = sys.argv[3] if len(sys.argv) > 3 else "2026-08-01"
    api_key = os.environ["STASHGAMMA_API_KEY"]

    data = await get_eod_data(symbol, date_from, date_to, api_key)
    print(f"{data['symbol']}: {data['count']} bars")
    for bar in data["bars"][:5]:
        print(bar)


if __name__ == "__main__":
    asyncio.run(main())
