"""Run the public SEC Event Intelligence MCP tool calls.

This runner does not require an API key. It calls the public
sec_demo_latest_filings and sec_subscription_info tools so an MCP integration
can confirm the remote server before production credentials are added.

    python3 sec-event-intelligence-mcp-first-call.py

Optional environment variables:

    MCP_URL="https://api.data-apis.com/mcp"
    LIMIT="3"
"""

from __future__ import annotations

import json
import os
import sys
import urllib.request


MCP_URL = os.environ.get("MCP_URL", "https://api.data-apis.com/mcp")
LIMIT = int(os.environ.get("LIMIT", "3"))


def post_json(label: str, payload: dict[str, object]) -> dict[str, object]:
    request = urllib.request.Request(
        MCP_URL,
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        result = json.loads(response.read().decode("utf-8"))
    if result.get("error"):
        print(f"{label} failed: {result['error']}", file=sys.stderr)
        raise SystemExit(1)
    print(f"{label}: ok")
    return result


def main() -> int:
    initialize = post_json(
        "initialize",
        {
            "jsonrpc": "2.0",
            "id": "mcp-first-call-initialize",
            "method": "initialize",
            "params": {
                "protocolVersion": "2025-11-25",
                "capabilities": {},
                "clientInfo": {
                    "name": "data-apis-sec-first-call",
                    "version": "1.0",
                },
            },
        },
    )
    server_info = (initialize.get("result") or {}).get("serverInfo") or {}
    print(f"server: {server_info.get('name', 'unknown')}")

    tools = post_json(
        "tools/list",
        {
            "jsonrpc": "2.0",
            "id": "mcp-first-call-tools-list",
            "method": "tools/list",
        },
    )
    tool_names = [
        tool.get("name")
        for tool in ((tools.get("result") or {}).get("tools") or [])
    ]
    print("tools:", ", ".join(name for name in tool_names if name))

    demo = post_json(
        "tools/call sec_demo_latest_filings",
        {
            "jsonrpc": "2.0",
            "id": "mcp-first-call-demo",
            "method": "tools/call",
            "params": {
                "name": "sec_demo_latest_filings",
                "arguments": {"limit": LIMIT},
            },
        },
    )
    demo_meta = (
        ((demo.get("result") or {}).get("structuredContent") or {}).get("meta")
        or {}
    )
    print("demo count:", demo_meta.get("count"))

    subscription = post_json(
        "tools/call sec_subscription_info",
        {
            "jsonrpc": "2.0",
            "id": "mcp-first-call-subscription",
            "method": "tools/call",
            "params": {"name": "sec_subscription_info", "arguments": {}},
        },
    )
    subscription_content = (
        (subscription.get("result") or {}).get("structuredContent") or {}
    )
    print("rapidapi:", subscription_content.get("rapidapiRestSubscribeUrl"))
    print("hosted mcp access:", subscription_content.get("hostedMcpAccessRequestUrl"))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
